serializertoxml.java

来自「java jdk 1.4的源码」· Java 代码 · 共 2,458 行 · 第 1/5 页

JAVA
2,458
字号
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation.  All rights  * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright *    notice, this list of conditions and the following disclaimer.  * * 2. Redistributions in binary form must reproduce the above copyright *    notice, this list of conditions and the following disclaimer in *    the documentation and/or other materials provided with the *    distribution. * * 3. The end-user documentation included with the redistribution, *    if any, must include the following acknowledgment:   *       "This product includes software developed by the *        Apache Software Foundation (http://www.apache.org/)." *    Alternately, this acknowledgment may appear in the software itself, *    if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must *    not be used to endorse or promote products derived from this *    software without prior written permission. For written  *    permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", *    nor may "Apache" appear in their name, without prior written *    permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com.  For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */package org.apache.xalan.serialize;import java.io.Writer;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;import java.io.IOException;import java.util.Enumeration;import java.util.Stack;import java.util.Vector;import java.util.Hashtable;import java.util.Properties;import java.util.BitSet;import org.xml.sax.*;import org.xml.sax.ext.LexicalHandler;import org.xml.sax.ext.DeclHandler;import org.w3c.dom.Node;import org.apache.xalan.serialize.Serializer;import org.apache.xalan.serialize.DOMSerializer;import org.apache.xml.utils.QName;import org.apache.xalan.templates.OutputProperties;import org.apache.xml.utils.BoolStack;import org.apache.xml.utils.TreeWalker;import org.apache.xml.utils.WrappedRuntimeException;import org.apache.xml.utils.SystemIDResolver;import org.apache.xalan.res.XSLTErrorResources;import org.apache.xalan.res.XSLMessages;import org.apache.xpath.res.XPATHErrorResources;import javax.xml.transform.Result;import javax.xml.transform.OutputKeys;/** * <meta name="usage" content="general"/> * SerializerToXML formats SAX-style events into XML. */public class SerializerToXML        implements ContentHandler, LexicalHandler, DeclHandler, Serializer,                   DOMSerializer{  /**   * The writer where the XML will be written.   */  protected Writer m_writer = null;  /** True if we control the buffer, and we should flush the output on endDocument. */  boolean m_shouldFlush = true;  //  /** The output stream where the result stream is written. */  //  protected OutputStream m_outputStream = System.out;  /**   * The character encoding.  Must match the encoding used for the printWriter.   */  protected String m_encoding = null;  /**   * Assume java encoding names are the same as the ISO encoding names if this is true.   */  static boolean javaEncodingIsISO = false;  /**   * Tells if we should write the XML declaration.   */  public boolean m_shouldNotWriteXMLHeader = false;  /**   * Tells the XML version, for writing out to the XML decl.   */  public String m_version = null;  /**   * A stack of Boolean objects that tell if the given element   * has children.   */  protected BoolStack m_elemStack = new BoolStack();  /** Stack to keep track of disabling output escaping. */  protected BoolStack m_disableOutputEscapingStates = new BoolStack();  /** True will be pushed, if characters should be in CDATA section blocks. */  protected BoolStack m_cdataSectionStates = new BoolStack();  /** List of QNames obtained from the xsl:output properties. */  protected Vector m_cdataSectionNames = null;  /** True if the current characters should be in CDATA blocks. */  protected boolean m_inCData = false;  /**   * Tell if the character escaping should be disabled for the current state.   *   * @return true if the character escaping should be disabled.   */  protected boolean isEscapingDisabled()  {    return m_disableOutputEscapingStates.peekOrFalse();  }  /**   * Tell if the characters in the current state should be put in   * cdata section blocks.   *   * @return true if the characters in the current state should be put in   * cdata section blocks.   */  protected boolean isCDataSection()  {    return m_inCData || m_cdataSectionStates.peekOrFalse();  }  /**   * Use the system line seperator to write line breaks.   */  protected final char[] m_lineSep =    System.getProperty("line.separator").toCharArray();  /**   * The length of the line seperator, since the write is done   * one character at a time.   */  protected final int m_lineSepLen = m_lineSep.length;  /**   * Output a system-dependent line break.   *   * @throws org.xml.sax.SAXException   */  protected final void outputLineSep() throws org.xml.sax.SAXException  {    try    {      m_writer.write(m_lineSep, 0, m_lineSepLen);    }    catch (IOException ioe)    {      throw new SAXException(ioe);    }  }  /**   * State flag to tell if preservation of whitespace   * is important.   */  protected boolean m_ispreserve = false;  /**   * Stack to keep track of whether or not we need to   * preserve whitespace.   */  protected BoolStack m_preserves = new BoolStack();  /**   * State flag that tells if the previous node processed   * was text, so we can tell if we should preserve whitespace.   */  protected boolean m_isprevtext = false;  /**   * Flag to tell if indenting (pretty-printing) is on.   */  protected boolean m_doIndent = false;  /**   * Flag to keep track of the indent amount.   */  protected int m_currentIndent = 0;  /**   * Amount to indent.   */  public int m_indentAmount = 0;  /**   * Current level of indent.   */  protected int level = 0;  /**   * Flag to signal that a newline should be added.   */  boolean m_startNewLine;  /**   * Flag to tell that we need to add the doctype decl,   * which we can't do until the first element is   * encountered.   */  boolean m_needToOutputDocTypeDecl = true;  /**   * The System ID for the doc type.   */  String m_doctypeSystem;  /**   * The public ID for the doc type.   */  String m_doctypePublic;  /**   * The standalone value for the doctype.   */  boolean m_standalone = false;  /**   * True if standalone was specified.   */  boolean m_standaloneWasSpecified = false;  /**   * The mediatype.  Not used right now.   */  String m_mediatype;  /**   * Tells if we're in an EntityRef event.   */  protected boolean m_inEntityRef = false;  /**   * Tells if we're in an internal document type subset.   */  private boolean m_inDoctype = false;  /**   * Map that tells which XML characters should have special treatment, and it   *  provides character to entity name lookup.   */  protected static CharInfo m_xmlcharInfo =    new CharInfo(CharInfo.XML_ENTITIES_RESOURCE);  /**   * Map that tells which characters should have special treatment, and it   *  provides character to entity name lookup.   */  protected CharInfo m_charInfo;  /** Table of user-specified char infos. */  private static Hashtable m_charInfos = null;  /**   * Flag to quickly tell if the encoding is UTF8.   */  boolean m_isUTF8 = false;  /**   * The maximum character size before we have to resort   * to escaping.   */  protected int m_maxCharacter = Encodings.getLastPrintable();  /**   * Add space before '/>' for XHTML.   */  public boolean m_spaceBeforeClose = false;  /** The xsl:output properties. */  protected Properties m_format;  /** Indicate whether running in Debug mode */  private static final boolean DEBUG = false;  /** This flag is set while receiving events from the external DTD */  private boolean m_inExternalDTD = false;  /**   * Default constructor.   */  public SerializerToXML()  {    m_charInfo = m_xmlcharInfo;  }  /**   * Copy properties from another SerializerToXML.   *   * @param xmlListener non-null reference to a SerializerToXML object.   */  public void CopyFrom(SerializerToXML xmlListener)  {    m_writer = xmlListener.m_writer;    // m_outputStream = xmlListener.m_outputStream;    m_encoding = xmlListener.m_encoding;    javaEncodingIsISO = xmlListener.javaEncodingIsISO;    m_shouldNotWriteXMLHeader = xmlListener.m_shouldNotWriteXMLHeader;    // m_shouldNotWriteXMLHeader = xmlListener.m_shouldNotWriteXMLHeader;    m_elemStack = xmlListener.m_elemStack;    // m_lineSep = xmlListener.m_lineSep;    // m_lineSepLen = xmlListener.m_lineSepLen;    m_ispreserve = xmlListener.m_ispreserve;    m_preserves = xmlListener.m_preserves;    m_isprevtext = xmlListener.m_isprevtext;    m_doIndent = xmlListener.m_doIndent;    m_currentIndent = xmlListener.m_currentIndent;    m_indentAmount = xmlListener.m_indentAmount;    level = xmlListener.level;    m_startNewLine = xmlListener.m_startNewLine;    m_needToOutputDocTypeDecl = xmlListener.m_needToOutputDocTypeDecl;    m_doctypeSystem = xmlListener.m_doctypeSystem;    m_doctypePublic = xmlListener.m_doctypePublic;    m_standalone = xmlListener.m_standalone;    m_mediatype = xmlListener.m_mediatype;    m_maxCharacter = xmlListener.m_maxCharacter;    m_spaceBeforeClose = xmlListener.m_spaceBeforeClose;    m_inCData = xmlListener.m_inCData;    // m_pos = xmlListener.m_pos;    m_pos = 0;  }  /**   * Initialize the serializer with the specified writer and output format.   * Must be called before calling any of the serialize methods.   *   * @param writer The writer to use   * @param format The output format   */  public synchronized void init(Writer writer, Properties format)  {    init(writer, format, false);  }  /**   * Initialize the serializer with the specified writer and output format.   * Must be called before calling any of the serialize methods.   *   * @param writer The writer to use   * @param format The output format   * @param shouldFlush True if the writer should be flushed at EndDocument.   */  private synchronized void init(Writer writer, Properties format,                                 boolean shouldFlush)  {    m_shouldFlush = shouldFlush;    m_writer = writer;    m_format = format;    m_cdataSectionNames =      OutputProperties.getQNameProperties(OutputKeys.CDATA_SECTION_ELEMENTS,                                          format);    m_indentAmount =      OutputProperties.getIntProperty(OutputProperties.S_KEY_INDENT_AMOUNT,                                      format);    m_doIndent = OutputProperties.getBooleanProperty(OutputKeys.INDENT,            format);    m_shouldNotWriteXMLHeader =      OutputProperties.getBooleanProperty(OutputKeys.OMIT_XML_DECLARATION,                                          format);    m_doctypeSystem = format.getProperty(OutputKeys.DOCTYPE_SYSTEM);    m_doctypePublic = format.getProperty(OutputKeys.DOCTYPE_PUBLIC);    m_standaloneWasSpecified = (null != format.get(OutputKeys.STANDALONE));    m_standalone = OutputProperties.getBooleanProperty(OutputKeys.STANDALONE,            format);    m_mediatype = format.getProperty(OutputKeys.MEDIA_TYPE);    if (null != m_doctypePublic)    {      if (m_doctypePublic.startsWith("-//W3C//DTD XHTML"))        m_spaceBeforeClose = true;    }    // initCharsMap();    if (null == m_encoding)      m_encoding =        Encodings.getMimeEncoding(format.getProperty(OutputKeys.ENCODING));    m_isUTF8 = m_encoding.equals(Encodings.DEFAULT_MIME_ENCODING);    m_maxCharacter = Encodings.getLastPrintable(m_encoding);    // Access this only from the Hashtable level... we don't want to     // get default properties.    String entitiesFileName =      (String) format.get(OutputProperties.S_KEY_ENTITIES);    if (null != entitiesFileName)    {      try      {        m_charInfo = null;        if (null == m_charInfos)        {          synchronized (m_xmlcharInfo)          {            if (null == m_charInfos)  // secondary check              m_charInfos = new Hashtable();          }        }        else        {          m_charInfo = (CharInfo) m_charInfos.get(entitiesFileName);        }        if (null == m_charInfo)        {          try          {            m_charInfo = new CharInfo(entitiesFileName);          }          catch(Exception e)          {          	m_charInfo = null;          }        }        if (null == m_charInfo)        {          String absoluteEntitiesFileName;          if (entitiesFileName.indexOf(':') < 0)          {            absoluteEntitiesFileName =              SystemIDResolver.getAbsoluteURIFromRelative(entitiesFileName);          }          else          {            absoluteEntitiesFileName =              SystemIDResolver.getAbsoluteURI(entitiesFileName, null);          }          m_charInfo = new CharInfo(absoluteEntitiesFileName);          m_charInfos.put(entitiesFileName, m_charInfo);        }      }

⌨️ 快捷键说明

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