xmldocument.java

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

JAVA
1,456
字号
        /**     * Writes the document in UTF-8 character encoding, as a well formed     * XML construct.     *     * @param out stream on which the document will be written      */    public void write (OutputStream out) throws IOException    {        Writer  writer = new OutputStreamWriter (out, "UTF8");        write (writer, "UTF-8");    }    /**     * Writes the document as a well formed XML construct.  If the     * encoding can be determined from the writer, that is used in     * the document's XML declaration.  The encoding name may first     * be transformed from a Java-internal form to a standard one;     * for example, Java's "UTF8" is the standard "UTF-8".     *     * <P> <em>Use of UTF-8 (or UTF-16) OutputStreamWriters is strongly     * encouraged. </em>  All other encodings may lose critical data,     * since the standard Java output writers substitute characters     * such as the question mark for data which they can't encode in     * the current output encoding.  The IETF and other organizations     * strongly encourage the use of UTF-8; also, all XML processors     * are guaranteed to support it.     *     * @see #write(java.io.Writer,java.lang.String)     *     * @param out stream on which the document will be written      */    public void write (Writer out) throws IOException    {        String  encoding = null;        if (out instanceof OutputStreamWriter)            encoding = java2std (((OutputStreamWriter)out).getEncoding ());        write (out, encoding);    }    //    // Try some of the common conversions from Java's internal names    // (which must fit in class names) to standard ones understood by    // most other code.  We use the IETF's preferred names; case is    // supposed to be ignored, note.    //    // package private     static String java2std (String encodingName)    {        if (encodingName == null)            return null;        //        // ISO-8859-N is a common family of 8 bit encodings;        // N=1 is the eight bit subset of UNICODE, and there        // seem to be at least drafts for some N >10.        //        if (encodingName.startsWith ("ISO8859_"))       // JDK 1.2            return "ISO-8859-" + encodingName.substring (8);        if (encodingName.startsWith ("8859_"))          // JDK 1.1            return "ISO-8859-" + encodingName.substring (5);        // XXX seven bit encodings ISO-2022-* ...        // XXX EBCDIC encodings ...         if ("ASCII7".equalsIgnoreCase (encodingName)                || "ASCII".equalsIgnoreCase (encodingName))            return "US-ASCII";                //        // All XML parsers _must_ support UTF-8 and UTF-16.        // (UTF-16 ~= ISO-10646-UCS-2 plus surrogate pairs)        //        if ("UTF8".equalsIgnoreCase (encodingName))            return "UTF-8";        if (encodingName.startsWith ("Unicode"))            return "UTF-16";                //        // Some common Japanese character sets.        //        if ("SJIS".equalsIgnoreCase (encodingName))            return "Shift_JIS";        if ("JIS".equalsIgnoreCase (encodingName))            return "ISO-2022-JP";        if ("EUCJIS".equalsIgnoreCase (encodingName))            return "EUC-JP";        // else we can't really do anything        return encodingName;    }        /**     * Writes the document in the specified encoding, and listing     * that encoding in the XML declaration.  The document will be     * well formed XML; at this time, it will not additionally be     * valid XML or standalone, since it includes no document type     * declaration.     *     * <P> Note that the document will by default be "pretty printed".     * Extra whitespace is added to indent children of elements according     * to their level of nesting, unless those elements have (or inherit)     * the <em>xml:space='preserve'</em> attribute value.  This space     * will be removed if, when the document is read back with DOM, a     * call to <em>ElementNode.normalize</em> is made.  To avoid this     * pretty printing, use a write context configured to disable it,     * or explicitly assign an <em>xml:space='preserve'</em> attribute to     * the root node of your document.     *     * <P> Also, if a SAX parser was used to construct this tree, data     * will have been discarded.  Most of that will be insignificant in     * terms of a "logical" view of document data:  comments, whitespace     * outside of the top level element, the exact content of the XML     * directive, and entity references were expanded.  However, <em>if a     * DOCTYPE declaration was provided, it was also discarded</em>.     * Such declarations will often be logically significant, due to the     * attribute value defaulting and normalization they can provide.     *     * <P> In general, DOM does not support "round tripping" data from     * XML to DOM and back without losing data about physical structures     * and DTD information.  "Logical structure" will be preserved.     *     * @see #setDoctype     * @see #writeXml     *     * @param out the writer to use when writing the document     * @param encoding the encoding name to use; this should be a     *  standard encoding name registered with the IANA (like "UTF-8")     *  not a Java-internal name (like "UTF8").     */    public void write (Writer out, String encoding)    throws IOException    {        //        // We put a pretty minimal declaration here, which is the        // best we can do given SAX input and DOM.  For the moment        // this precludes our generating "standalone" annotations.        //        out.write ("<?xml version=\"1.0\"");        if (encoding != null) {            out.write (" encoding=\"");            out.write (encoding);            out.write ('\"');        }        out.write ("?>");        out.write (eol);        out.write (eol);        writeChildrenXml (createWriteContext (out, 0));        out.write (eol);        out.flush ();    }    /**     * Returns an XML write context set up not to pretty-print,     * and which knows about the entities defined for this document.     *     * @param out stream on which the document will be written      */    public XmlWriteContext createWriteContext (Writer out)    {        return new ExtWriteContext (out);    }    /**     * Returns an XML write context which pretty-prints output starting     * at a specified indent level, and which knows about the entities     * defined for this document.     *     * @param out stream on which the document will be written      * @param level initial indent level for pretty-printing     */    public XmlWriteContext createWriteContext (Writer out, int level)    {        return new ExtWriteContext (out, level);    }    /**     * Writes the document out using the specified context, using     * an encoding name derived from the stream in the context where     * that is possible.     *     * @see #createWriteContext(java.io.Writer)     * @see #createWriteContext(java.io.Writer,int)     *     * @param context describes how to write the document     */    public void writeXml (XmlWriteContext context) throws IOException    {        Writer  out = context.getWriter ();        String  encoding = null;        //        // XXX as above, it should be possible to be "told" this name        // in order to use more standard names.  We can pretty print,        // or we can use the right encoding name; not both!!        //        if (out instanceof OutputStreamWriter)            encoding = java2std (((OutputStreamWriter)out).getEncoding ());        //        // We put a pretty minimal declaration here, which is the        // best we can do given SAX input and DOM.  For the moment        // this precludes our generating "standalone" annotations.        //        out.write ("<?xml version=\"1.0\"");        if (encoding != null) {            out.write (" encoding=\"");            out.write (encoding);            out.write ('\"');        }        out.write ("?>");        out.write (eol);        out.write (eol);        writeChildrenXml (context);    }    /**     * Writes all the child nodes of the document, following each one     * with the end-of-line string in use in this environment.     */    public void writeChildrenXml (XmlWriteContext context) throws IOException    {        int     length = getLength ();        Writer  out = context.getWriter ();        if (length == 0)            return;        for (int i = 0; i < length; i++) {            ((NodeBase)item (i)).writeXml (context);            out.write (eol);        }    }    // package private -- overrides base class method    void checkChildType (int type)    throws DOMException    {        switch (type) {          case ELEMENT_NODE:          case PROCESSING_INSTRUCTION_NODE:          case COMMENT_NODE:          case DOCUMENT_TYPE_NODE:            return;          default:            throw new DomEx (DomEx.HIERARCHY_REQUEST_ERR);        }    }    /**     * Assigns the URI associated with the document, which is its     * system ID.     *     * @param uri The document's system ID, as used when storing     *  the document.     */    final public void setSystemId (String uri)    {        systemId = uri;    }    /**     * Returns system ID associated with the document, or null if     * this is unknown.     *     * <P> This URI should not be used when interpreting relative URIs,     * since the document may be partially stored in external parsed     * entities with different base URIs.  Instead, use methods in the     * <em>XmlReadable</em> interface as the document is being parsed,     * so that the correct base URI is available.     */    final public String getSystemId ()    {        return systemId;    }    // DOM support    /**     * DOM:  Appends the specified child node to the document.  Only one     * element or document type node may be a child of a document.     *     * @param node the node to be appended.     */    public Node appendChild (Node n)    throws DOMException    {        if (n instanceof Element && getDocumentElement () != null)            throw new DomEx (DomEx.HIERARCHY_REQUEST_ERR);        if (n instanceof DocumentType && getDoctype () != null)            throw new DomEx (DomEx.HIERARCHY_REQUEST_ERR);        return super.appendChild (n);    }    /**     * DOM:  Inserts the specified child node into the document.  Only one     * element or document type node may be a child of a document.     *     * @param n the node to be inserted.     * @param refNode the node before which this is to be inserted     */    public Node insertBefore (Node n, Node refNode)    throws DOMException    {        if (!replaceRootElement && n instanceof Element &&             getDocumentElement () != null)            throw new DomEx (DomEx.HIERARCHY_REQUEST_ERR);        if (!replaceRootElement && n instanceof DocumentType             && getDoctype () != null)            throw new DomEx (DomEx.HIERARCHY_REQUEST_ERR);        return super.insertBefore (n, refNode);    }    /**     * <b>DOM:</b>  Replaces the specified child with the new node,     * returning the original child or throwing an exception.     * The new child must belong to this particular document.     *     * @param newChild the new child to be inserted     * @param refChild node which is to be replaced     */    public Node replaceChild (Node newChild, Node refChild)    throws DOMException    {        if (newChild instanceof DocumentFragment ) {            int elemCount = 0;            int docCount = 0;            replaceRootElement = false;            ParentNode frag = (ParentNode) newChild;            Node temp;            int i = 0;            while ((temp = frag.item (i)) != null) {                if (temp instanceof Element)                     elemCount++;                 else if (temp instanceof DocumentType)                    docCount++;                i++;            }            if (elemCount > 1 || docCount > 1)                throw new DomEx (DomEx.HIERARCHY_REQUEST_ERR);            else                 replaceRootElement = true;        }        return super.replaceChild (newChild, refChild);    }    /** DOM: Returns the DOCUMENT_NODE node type constant. */    final public short getNodeType () { return DOCUMENT_NODE; }    /** DOM: returns the document type (DTD) */    final public DocumentType getDoctype ()    {        // We ignore comments, PIs, whitespace, etc

⌨️ 快捷键说明

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