xmlprinter.java

来自「RESIN 3.2 最新源码」· Java 代码 · 共 1,724 行 · 第 1/3 页

JAVA
1,724
字号
/* * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT.  See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the *   Free SoftwareFoundation, Inc. *   59 Temple Place, Suite 330 *   Boston, MA 02111-1307  USA * * @author Scott Ferguson */package com.caucho.xml2;import com.caucho.java.LineMap;import com.caucho.log.Log;import com.caucho.util.CharBuffer;import com.caucho.util.IntMap;import com.caucho.util.L10N;import com.caucho.vfs.EnclosedWriteStream;import com.caucho.vfs.Path;import com.caucho.vfs.Vfs;import com.caucho.vfs.WriteStream;import org.w3c.dom.*;import org.xml.sax.Locator;import java.io.IOException;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.io.Writer;import java.util.ArrayList;import java.util.HashMap;import java.util.logging.Logger;/** * Controls printing of XML documents. * * Typical use: * <code><pre> * Node node = ...; * * OutputStream os = Vfs.openWrite("test.xml"); * XmlPrinter printer = new XmlPrinter(os); * * printer.printXml(node); * </pre></code> */public class XmlPrinter implements XMLWriter {  static final Logger log = Log.open(XmlPrinter.class);  static final L10N L = new L10N(XmlPrinter.class);    private static final int NO_PRETTY = 0;  private static final int INLINE = 1;  private static final int NO_INDENT = 2;  private static final int PRE = 3;  private static final char OMITTED_SPACE = 0;  private static final char OMITTED_NEWLINE = 1;  private static final char OMITTED = 2;  private static final char NULL_SPACE = 3;  private static final char SPACE = 4;  private static final char NEWLINE = 5;  private static final char WHITESPACE = 6;  private static final int ALWAYS_EMPTY = 1;  private static final int EMPTY_IF_EMPTY = 2;    private static IntMap _empties;  private static HashMap<String,String> _booleanAttrs;  private static HashMap<String,String> _verbatimTags;  private static IntMap _prettyMap;  private WriteStream _os;  private char []_buffer = new char[256];  private int _capacity = _buffer.length;  private int _length;  boolean _isAutomaticMethod = true;  boolean _isTop = true;  boolean _isJsp = false;  String _encoding;  String _method;  boolean _isText;  boolean _isHtml;  boolean _inHead;  String _version;  boolean _isAutomaticPretty = true;  boolean _isPretty;  int _indent;  int _preCount;  int _lastTextChar = NULL_SPACE;  boolean _hasMetaContentType = false;  boolean _includeContentType = true;  boolean _printDeclaration;    String _standalone;  String _systemId;  String _publicId;  private ExtendedLocator _locator;    boolean _escapeText = true;  boolean _inVerbatim = false;    private HashMap<String,String> _namespace;  private HashMap<String,String> _cdataElements;  private Entities _entities;  private String _mimeType;  private ArrayList<String> _prefixList;    private ArrayList<String> _attributeNames = new ArrayList<String>();  private ArrayList<String> _attributeValues = new ArrayList<String>();  private char []_cbuf = new char[256];  private char []_abuf = new char[256];    private LineMap _lineMap;  private int _line;  private String _srcFilename;  private int _srcLine;  private String _currentElement;  private Document _currentDocument;  private boolean _isEnclosedStream;  /**   * Create an XmlPrinter.  Using this API, you'll need to use   * printer.init(os) to assign an output stream.   */  public XmlPrinter()  {  }  /**   * Creates a new XmlPrinter writing to an output stream.   *   * @param os output stream serving as the destination   */  public XmlPrinter(OutputStream os)  {    if (os instanceof WriteStream)      init((WriteStream) os);    else if (os instanceof EnclosedWriteStream)      init(((EnclosedWriteStream) os).getWriteStream());    else {      _isEnclosedStream = true;      WriteStream ws = Vfs.openWrite(os);      try {        ws.setEncoding("UTF-8");      } catch (UnsupportedEncodingException e) {      }      init(ws);    }  }  /**   * Creates a new XmlPrinter writing to a writer.   *   * @param writer destination of the serialized node   */  public XmlPrinter(Writer writer)  {    if (writer instanceof EnclosedWriteStream)      init(((EnclosedWriteStream) writer).getWriteStream());    else {      _isEnclosedStream = true;      WriteStream ws = Vfs.openWrite(writer);      init(ws);    }  }  /**   * Initialize the XmlPrinter with the write stream.   *   * @param os WriteStream containing the results.   */  public void init(WriteStream os)  {    _os = os;    init();  }  /**   * Initialize the XmlWriter in preparation for serializing a new XML.   */  void init()  {    String encoding = null;    if (_os != null)      encoding = _os.getEncoding();    _length = 0;    if (encoding == null ||	encoding.equals("US-ASCII") || encoding.equals("ISO-8859-1"))      _entities = XmlLatin1Entities.create();    else      _entities = XmlEntities.create();    _encoding = encoding;    _namespace = new HashMap<String,String>();    _line = 1;    _isTop = true;    _hasMetaContentType = false;    _attributeNames.clear();    _attributeValues.clear();  }  /**   * Prints the node as XML.  The destination stream has already been   * set using init() or in the constructor.   *   * @param node source DOM node   */  public static void print(Path path, Node node)    throws IOException  {    WriteStream os = path.openWrite();    try {      new XmlPrinter(os).printXml(node);    } finally {      os.close();    }  }  /**   * Prints the node as XML.  The destination stream has already been   * set using init() or in the constructor.   *   * @param node source DOM node   */  public void printXml(Node node)    throws IOException  {    _isAutomaticMethod = false;    ((QAbstractNode) node).print(this);    flush();  }  /**   * Prints the node and children as HTML   *   * @param node the top node to print   */  public void printHtml(Node node)    throws IOException  {    setMethod("html");    setVersion("4.0");    ((QAbstractNode) node).print(this);    flush();  }  /**   * Prints the node and children as XML, automatically indending   *   * @param node the top node to print   */  public void printPrettyXml(Node node)    throws IOException  {    _isAutomaticMethod = false;    setPretty(true);    ((QAbstractNode) node).print(this);    flush();  }  /**   * Prints the node as XML to a string.   *   * @param node the source node   * @return a string containing the XML.   */  public String printString(Node node)    throws IOException  {    CharBuffer cb = CharBuffer.allocate();    _os = Vfs.openWrite(cb);    init(_os);    try {      ((QAbstractNode) node).print(this);    } finally {      flush();      _os.close();    }    return cb.close();  }  /**   * Sets to true if XML entities like &lt; should be escaped as &amp;lt;.   * The default is true.   *   * @param escapeText set to true if entities should be escaped.   */  public void setEscaping(boolean escapeText)  {    if (! _isText)      _escapeText = escapeText;  }    /**   * Returns the current XML escaping.  If true, entities like &lt;   * will be escaped as &amp;lt;.   *   * @return true if entities should be escaped.   */  public boolean getEscaping()  {    return _escapeText;  }  /**   * Sets the output methods, like the XSL &lt;xsl:output method='method'/>.   */  public void setMethod(String method)  {    _method = method;    if (method == null) {      _isAutomaticMethod = true;      _isHtml = false;    } else if (method.equals("html")) {      _isAutomaticMethod = false;      _isHtml = true;      if (_isAutomaticPretty)        _isPretty = true;    } else if (method.equals("text")) {      _isAutomaticMethod = false;      _isText = true;      _escapeText = false;    } else {      _isAutomaticMethod = false;      _isHtml = false;    }  }    /**   * Sets the XML/HTML version of the output file.   *   * @param version the output version   */  public void setVersion(String version)  {    _version = version;  }    /**   * Sets the character set encoding for the output file.   *   * @param encoding the mime name of the output encoding   */  public void setEncoding(String encoding)  {    _encoding = encoding;    try {      if (encoding != null) {        _os.setEncoding(encoding);	if (encoding.equals("US-ASCII") || encoding.equals("ISO-8859-1"))	  _entities = XmlLatin1Entities.create();	else	  _entities = XmlEntities.create();      }    } catch (Exception e) {    }  }  public void setMimeType(String mimeType)  {    _mimeType = mimeType;    if (_method == null && mimeType != null && mimeType.equals("text/html"))      setMethod("html");  }  /**   * Set true if this is JSP special cased.   */  public void setJSP(boolean isJsp)  {    _isJsp = isJsp;  }  /**   * True if this is JSP special cased.   */  public boolean isJSP()  {    return _isJsp;  }  /**   * Returns true if the printer is printing HTML.   */  boolean isHtml()  {    return _isHtml;  }  /**   * Set to true if the printer should add whitespace to 'pretty-print'   * the output.   *   * @param isPretty if true, add spaces for printing   */  public void setPretty(boolean isPretty)  {    _isPretty = isPretty;    _isAutomaticPretty = false;  }  /**   * Returns true if the printer is currently pretty-printing the output.   */  public boolean isPretty()  {    return _isPretty;  }    public void setPrintDeclaration(boolean printDeclaration)  {    _printDeclaration = printDeclaration;  }    boolean getPrintDeclaration()  {    return _printDeclaration;  }    public void setStandalone(String standalone)  {    _standalone = standalone;  }    String getStandalone()  {    return _standalone;  }    public void setSystemId(String id)  {    _systemId = id;  }    String getSystemId()  {    return _systemId;  }  /**   * Set true if the printer should automatically add the   * &lt;meta content-type> to HTML.   */  public void setIncludeContentType(boolean include)  {    _includeContentType = include;  }    /**   * Return true if the printer should automatically add the   * &lt;meta content-type> to HTML.   */  public boolean getIncludeContentType()  {    return _includeContentType;  }    public void setPublicId(String id)  {    _publicId = id;  }    String getPublicId()  {    return _publicId;  }  public Path getPath()  {    if (_os instanceof WriteStream)      return ((WriteStream) _os).getPath();    else      return null;  }  /**   * Creates a new line map.   */  public void setLineMap(String filename)  {    _lineMap = new LineMap(filename);  }  public LineMap getLineMap()  {    return _lineMap;  }  public void addCdataElement(String elt)  {    if (_cdataElements == null)      _cdataElements = new HashMap<String,String>();    _cdataElements.put(elt, "");  }  public void print(Node node)    throws IOException  {    if (node instanceof QAbstractNode)      ((QAbstractNode) node).print(this);    else {      printNode(node);    }        if (_isEnclosedStream)      _os.flush();  }  public void printNode(Node node)    throws IOException  {    if (node == null)      return;    switch (node.getNodeType()) {    case Node.DOCUMENT_NODE:      startDocument((Document) node);      for (Node child = node.getFirstChild();           child != null;           child = child.getNextSibling())        printNode(child);      endDocument();      break;          case Node.ELEMENT_NODE: {      Element elt = (Element) node;            startElement(elt.getNamespaceURI(),                   elt.getLocalName(),                   elt.getNodeName());      NamedNodeMap attrs = elt.getAttributes();      int len = attrs.getLength();      for (int i = 0; i < len; i++) {        Attr attr = (Attr) attrs.item(i);        attribute(attr.getNamespaceURI(),

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?