tostream.java

来自「JAVA 所有包」· Java 代码 · 共 2,016 行 · 第 1/5 页

JAVA
2,016
字号
     * Escape and writer.write a character.     *     * @param ch character to be escaped.     * @param i index into character array.     * @param chars non-null reference to character array.     * @param len length of chars.     * @param fromTextNode true if the characters being processed are     * from a text node, false if the characters being processed are from     * an attribute value.     * @param escLF true if the linefeed should be escaped.     *     * @return i+1 if a character was written, i+2 if two characters     * were written out, else return i.     *     * @throws org.xml.sax.SAXException     */    protected int accumDefaultEscape(        Writer writer,        char ch,        int i,        char[] chars,        int len,        boolean fromTextNode,        boolean escLF)        throws IOException    {        int pos = accumDefaultEntity(writer, ch, i, chars, len, fromTextNode, escLF);        if (i == pos)        {            if (Encodings.isHighUTF16Surrogate(ch))            {                // Should be the UTF-16 low surrogate of the hig/low pair.                char next;                // Unicode code point formed from the high/low pair.                int codePoint = 0;                if (i + 1 >= len)                {                    throw new IOException(                        Utils.messages.createMessage(                            MsgKey.ER_INVALID_UTF16_SURROGATE,                            new Object[] { Integer.toHexString(ch)}));                    //"Invalid UTF-16 surrogate detected: "                    //+Integer.toHexString(ch)+ " ?");                }                else                {                    next = chars[++i];                    if (!(Encodings.isLowUTF16Surrogate(next)))                        throw new IOException(                            Utils.messages.createMessage(                                MsgKey                                    .ER_INVALID_UTF16_SURROGATE,                                new Object[] {                                    Integer.toHexString(ch)                                        + " "                                        + Integer.toHexString(next)}));                    //"Invalid UTF-16 surrogate detected: "                    //+Integer.toHexString(ch)+" "+Integer.toHexString(next));                    codePoint = Encodings.toCodePoint(ch,next);                }                writer.write("&#");                writer.write(Integer.toString(codePoint));                writer.write(';');                pos += 2; // count the two characters that went into writing out this entity            }            else            {                /*  This if check is added to support control characters in XML 1.1.                 *  If a character is a Control Character within C0 and C1 range, it is desirable                 *  to write it out as Numeric Character Reference(NCR) regardless of XML Version                 *  being used for output document.                 */                 if (isCharacterInC0orC1Range(ch) ||                         (XMLVERSION11.equals(getVersion()) && isNELorLSEPCharacter(ch)))                {                    writer.write("&#");                    writer.write(Integer.toString(ch));                    writer.write(';');                }                else if ((!escapingNotNeeded(ch) ||                     (  (fromTextNode && m_charInfo.isSpecialTextChar(ch))                     || (!fromTextNode && m_charInfo.isSpecialAttrChar(ch))))                 && m_elemContext.m_currentElemDepth > 0)                {                    writer.write("&#");                    writer.write(Integer.toString(ch));                    writer.write(';');                }                else                {                    writer.write(ch);                }                pos++;  // count the single character that was processed            }        }        return pos;    }    /**     * Receive notification of the beginning of an element, although this is a     * SAX method additional namespace or attribute information can occur before     * or after this call, that is associated with this element.     *     *     * @param namespaceURI The Namespace URI, or the empty string if the     *        element has no Namespace URI or if Namespace     *        processing is not being performed.     * @param localName The local name (without prefix), or the     *        empty string if Namespace processing is not being     *        performed.     * @param name The element type name.     * @param atts The attributes attached to the element, if any.     * @throws org.xml.sax.SAXException Any SAX exception, possibly     *            wrapping another exception.     * @see org.xml.sax.ContentHandler#startElement     * @see org.xml.sax.ContentHandler#endElement     * @see org.xml.sax.AttributeList     *     * @throws org.xml.sax.SAXException     */    public void startElement(        String namespaceURI,        String localName,        String name,        Attributes atts)        throws org.xml.sax.SAXException    {        if (m_inEntityRef)            return;        if (m_needToCallStartDocument)        {            startDocumentInternal();            m_needToCallStartDocument = false;        }        else if (m_cdataTagOpen)            closeCDATA();        try        {            if ((true == m_needToOutputDocTypeDecl)                && (null != getDoctypeSystem()))            {                outputDocTypeDecl(name, true);            }            m_needToOutputDocTypeDecl = false;                    /* before we over-write the current elementLocalName etc.             * lets close out the old one (if we still need to)             */            if (m_elemContext.m_startTagOpen)            {                closeStartTag();                m_elemContext.m_startTagOpen = false;            }            if (namespaceURI != null)                ensurePrefixIsDeclared(namespaceURI, name);                            m_ispreserve = false;            if (shouldIndent() && m_startNewLine)            {                indent();            }            m_startNewLine = true;            final java.io.Writer writer = m_writer;            writer.write('<');            writer.write(name);        }        catch (IOException e)        {            throw new SAXException(e);        }             // process the attributes now, because after this SAX call they might be gone        if (atts != null)            addAttributes(atts);                     m_elemContext = m_elemContext.push(namespaceURI,localName,name);        m_isprevtext = false;        if (m_tracer != null){            firePseudoAttributes();        }                }    /**      * Receive notification of the beginning of an element, additional      * namespace or attribute information can occur before or after this call,      * that is associated with this element.      *      *      * @param elementNamespaceURI The Namespace URI, or the empty string if the      *        element has no Namespace URI or if Namespace      *        processing is not being performed.      * @param elementLocalName The local name (without prefix), or the      *        empty string if Namespace processing is not being      *        performed.      * @param elementName The element type name.      * @throws org.xml.sax.SAXException Any SAX exception, possibly      *            wrapping another exception.      * @see org.xml.sax.ContentHandler#startElement      * @see org.xml.sax.ContentHandler#endElement      * @see org.xml.sax.AttributeList      *      * @throws org.xml.sax.SAXException      */    public void startElement(        String elementNamespaceURI,        String elementLocalName,        String elementName)        throws SAXException    {        startElement(elementNamespaceURI, elementLocalName, elementName, null);    }    public void startElement(String elementName) throws SAXException    {        startElement(null, null, elementName, null);    }    /**     * Output the doc type declaration.     *     * @param name non-null reference to document type name.     * NEEDSDOC @param closeDecl     *     * @throws java.io.IOException     */    void outputDocTypeDecl(String name, boolean closeDecl) throws SAXException    {        if (m_cdataTagOpen)            closeCDATA();        try        {            final java.io.Writer writer = m_writer;            writer.write("<!DOCTYPE ");            writer.write(name);            String doctypePublic = getDoctypePublic();            if (null != doctypePublic)            {                writer.write(" PUBLIC \"");                writer.write(doctypePublic);                writer.write('\"');            }            String doctypeSystem = getDoctypeSystem();            if (null != doctypeSystem)            {                if (null == doctypePublic)                    writer.write(" SYSTEM \"");                else                    writer.write(" \"");                writer.write(doctypeSystem);                if (closeDecl)                {                    writer.write("\">");                    writer.write(m_lineSep, 0, m_lineSepLen);                    closeDecl = false; // done closing                }                else                    writer.write('\"');            }            boolean dothis = false;            if (dothis)            {                // at one point this code seemed right,                // but not anymore - Brian M.                if (closeDecl)                {                    writer.write('>');                    writer.write(m_lineSep, 0, m_lineSepLen);                }            }        }        catch (IOException e)        {            throw new SAXException(e);        }    }    /**     * Process the attributes, which means to write out the currently     * collected attributes to the writer. The attributes are not     * cleared by this method     *      * @param writer the writer to write processed attributes to.     * @param nAttrs the number of attributes in m_attributes      * to be processed     *     * @throws java.io.IOException     * @throws org.xml.sax.SAXException     */    public void processAttributes(java.io.Writer writer, int nAttrs) throws IOException, SAXException    {            /* real SAX attributes are not passed in, so process the              * attributes that were collected after the startElement call.             * _attribVector is a "cheap" list for Stream serializer output             * accumulated over a series of calls to attribute(name,value)             */            String encoding = getEncoding();            for (int i = 0; i < nAttrs; i++)            {                // elementAt is JDK 1.1.8                final String name = m_attributes.getQName(i);                final String value = m_attributes.getValue(i);                writer.write(' ');                writer.write(name);                writer.write("=\"");                writeAttrString(writer, value, encoding);                writer.write('\"');            }    }    /**     * Returns the specified <var>string</var> after substituting <VAR>specials</VAR>,     * and UTF-16 surrogates for chracter references <CODE>&amp;#xnn</CODE>.     *     * @param   string      String to convert to XML format.     * @param   encoding    CURRENTLY NOT IMPLEMENTED.     *     * @throws java.io.IOException     */    public void writeAttrString(        Writer writer,        String string,        String encoding)        throws IOException    {        final int len = string.length();        if (len > m_attrBuff.length)        {           m_attrBuff = new char[len*2 + 1];                     }        string.getChars(0,len, m_attrBuff, 0);           final char[] stringChars = m_attrBuff;        for (int i = 0; i < len; i++)        {            char ch = stringChars[i];            if (escapingNotNeeded(ch) && (!m_charInfo.isSpecialAttrChar(ch)))            {                writer.write(ch);            }            else            { // I guess the parser doesn't normalize cr/lf in attributes. -sb//                if ((CharInfo.S_CARRIAGERETURN == ch)//                    && ((i + 1) < len)//                    && (CharInfo.S_LINEFEED == stringChars[i + 1]))//                {//                    i++;//                    ch = CharInfo.S_LINEFEED;//                }                accumDefaultEscape(writer, ch, i, stringChars, len, false, true);            }        }    }    /**     * Receive notification of the end of an element.     *     *     * @param namespaceURI The Namespace URI, or the empty string if the     *        element has no Namespace URI or if Namespace     *        processing is not being performed.     * @param localName The local name (without prefix), or the     *        empty string if Namespace processing is not being     *        performed.     * @param name The element type name     * @throws org.xml.sax.SAXException Any SAX exception, possibly     *            wrapping another exception.     *     * @throws org.xml.sax.SAXException     */    public void endElement(String namespaceURI, String localName, String name)        throws org.xml.sax.SAXException    {                if (m_inEntityRef)            return;        // namespaces decla

⌨️ 快捷键说明

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