domserializerimpl.java

来自「JAVA的一些源码 JAVA2 STANDARD EDITION DEVELO」· Java 代码 · 共 1,175 行 · 第 1/4 页

JAVA
1,175
字号
        Document fDocument =(node.getNodeType() == Node.DOCUMENT_NODE)                ? (Document) node                : node.getOwnerDocument();        // this should run under JDK 1.1.8...        try {            getXmlVersion =                fDocument.getClass().getMethod("getXmlVersion", new Class[] {});            if (getXmlVersion != null) {                ver = (String) getXmlVersion.invoke(fDocument, null);            }        } catch (Exception e) {            // no way to test the version...            // ignore the exception        }        if (ver != null && ver.equals("1.1")) {            if (xml11Serializer == null) {                xml11Serializer = new XML11Serializer();                initSerializer(xml11Serializer);            }            // copy setting from "main" serializer to XML 1.1 serializer            copySettings(serializer, xml11Serializer);            ser = xml11Serializer;        } else {            ser = serializer;        }                try {            Method getEncoding =                fDocument.getClass().getMethod("getInputEncoding", new Class[] {});            if (getEncoding != null) {                encoding = (String) getEncoding.invoke(fDocument, null);            }        } catch (Exception e) {            // ignore the exception        }        if (encoding == null) {            try {                Method getEncoding =                    fDocument.getClass().getMethod("getXmlEncoding", new Class[] {});                if (getEncoding != null) {                    encoding = (String) getEncoding.invoke(fDocument, null);                }            } catch (Exception e) {                // ignore the exception            }            if (encoding == null) {                encoding = "UTF-8";            }        }        try {            prepareForSerialization(ser, node);            ser._format.setEncoding(encoding);                        // URI was specified. Handle relative URIs.            String expanded = XMLEntityManager.expandSystemId(URI, null, true);            URL url = new URL(expanded != null ? expanded : URI);            OutputStream out = null;            String protocol = url.getProtocol();            String host = url.getHost();            // Use FileOutputStream if this URI is for a local file.            if (protocol.equals("file")                 && (host == null || host.length() == 0 || host.equals("localhost"))) {                // REVISIT: We have to decode %nn sequences. For                // now files containing spaces and other characters                // which were escaped in the URI will fail. -- mrglavas                out = new FileOutputStream(new File(url.getPath()));            }            // Try to write to some other kind of URI. Some protocols            // won't support this, though HTTP should work.            else {                URLConnection urlCon = url.openConnection();                urlCon.setDoInput(false);                urlCon.setDoOutput(true);                urlCon.setUseCaches(false); // Enable tunneling.                if (urlCon instanceof HttpURLConnection) {                    // The DOM L3 LS CR says if we are writing to an HTTP URI                    // it is to be done with an HTTP PUT.                     HttpURLConnection httpCon = (HttpURLConnection) urlCon;                    httpCon.setRequestMethod("PUT");                }                out = urlCon.getOutputStream();            }            ser.setOutputByteStream(out);            if (node.getNodeType() == Node.DOCUMENT_NODE)                ser.serialize((Document) node);            else if (node.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE)                ser.serialize((DocumentFragment) node);            else if (node.getNodeType() == Node.ELEMENT_NODE)                ser.serialize((Element) node);            else                return false;        } catch (RuntimeException e) {            if (e == DOMNormalizer.abort){                // stopped at user request                return false;            }            throw new LSException(LSException.SERIALIZE_ERR, e.toString());                    } catch (Exception e) {            if (ser.fDOMErrorHandler != null) {                DOMErrorImpl error = new DOMErrorImpl();                error.fException = e;                error.fMessage = e.getMessage();                error.fSeverity = DOMError.SEVERITY_ERROR;                ser.fDOMErrorHandler.handleError(error);            }            throw new LSException(LSException.SERIALIZE_ERR, e.toString());        }        return true;    } //writeURI            //    //  Private methods    //    private void prepareForSerialization(XMLSerializer ser, Node node) {        ser.reset();        ser.features = features;        ser.fDOMErrorHandler = fErrorHandler;        ser.fNamespaces = (features & NAMESPACES) !=0;        ser._format.setOmitComments((features & COMMENTS)==0);        ser._format.setOmitXMLDeclaration((features & XMLDECL) == 0);            if ((features & WELLFORMED) != 0) {            // REVISIT: this is inefficient implementation of well-formness. Instead, we should check            // well-formness as we serialize the tree            Node next, root;            root = node;            Method versionChanged;            boolean verifyNames = true;            Document document =(node.getNodeType() == Node.DOCUMENT_NODE)                    ? (Document) node                    : node.getOwnerDocument();            try {                versionChanged = document.getClass().getMethod("isXMLVersionChanged()", new Class[] {});                if (versionChanged != null) {                    verifyNames = ((Boolean)versionChanged.invoke(document, null)).booleanValue();                }            } catch (Exception e) {                //no way to test the version...                //ignore the exception            }            while (node != null) {              verify(node, verifyNames, false);              // Move down to first child              next = node.getFirstChild();              // No child nodes, so walk tree              while (next == null) {                // Move to sibling if possible.                next = node.getNextSibling();                if (next == null){                    node = node.getParentNode();                    if (root == node){                        next = null;                        break;                                       }                    next = node.getNextSibling();                }              }              node = next;          }         }    }            private void verify (Node node, boolean verifyNames, boolean xml11Version){        int type = node.getNodeType();        fLocator.fRelatedNode = node;        boolean wellformed;        switch (type) {             case Node.DOCUMENT_NODE:{                break;            }            case Node.DOCUMENT_TYPE_NODE:{                break;            }            case Node.ELEMENT_NODE:{                               if (verifyNames){                    if((features & NAMESPACES) != 0){                        wellformed = CoreDocumentImpl.isValidQName(node.getPrefix() , node.getLocalName(), xml11Version) ;                    }                    else{                        wellformed = CoreDocumentImpl.isXMLName(node.getNodeName() , xml11Version);                    }                    if (!wellformed){                            if (!wellformed){                                if (fErrorHandler != null) {                                    String msg = DOMMessageFormatter.formatMessage(                                        DOMMessageFormatter.DOM_DOMAIN,                                         "wf-invalid-character-in-node-name",                                         new Object[]{"Element", node.getNodeName()});                                        DOMNormalizer.reportDOMError(fErrorHandler, fError, fLocator, msg, DOMError.SEVERITY_FATAL_ERROR,                                         "wf-invalid-character-in-node-name");                                }                                                    }                                           }                }                                AttributeMap attributes = (node.hasAttributes()) ? (AttributeMap) node.getAttributes() : null;                 if (attributes != null) {                    for (int i = 0; i < attributes.getLength(); ++i) {                        Attr attr = (Attr) attributes.item(i);                        fLocator.fRelatedNode = attr;                        DOMNormalizer.isAttrValueWF( fErrorHandler, fError, fLocator,                                       attributes,(AttrImpl) attr, attr.getValue(), xml11Version);                        if (verifyNames) {                            wellformed = CoreDocumentImpl.isXMLName( attr.getNodeName(), xml11Version);                            if (!wellformed) {                                    String msg =                                        DOMMessageFormatter.formatMessage(                                            DOMMessageFormatter.DOM_DOMAIN,                                            "wf-invalid-character-in-node-name",                                            new Object[] { "Attr", node.getNodeName()});                                    DOMNormalizer.reportDOMError( fErrorHandler, fError, fLocator, msg, DOMError.SEVERITY_FATAL_ERROR,                                        "wf-invalid-character-in-node-name");                            }                        }                    }                }                                break;            }                case Node.COMMENT_NODE: {            // only verify well-formness if comments included in the tree            if ((features & COMMENTS) != 0)                DOMNormalizer.isCommentWF(fErrorHandler, fError, fLocator, ((Comment)node).getData(), xml11Version);            break;        }        case Node.ENTITY_REFERENCE_NODE: {            // only if entity is preserved in the tree            if (verifyNames && (features & ENTITIES) != 0){                CoreDocumentImpl.isXMLName(node.getNodeName() , xml11Version);            }            break;                    }        case Node.CDATA_SECTION_NODE: {            // verify content            DOMNormalizer.isXMLCharWF(fErrorHandler, fError, fLocator, node.getNodeValue(), xml11Version);            // the ]]> string will be checked during serialization            break;        }        case Node.TEXT_NODE:{            DOMNormalizer.isXMLCharWF(fErrorHandler, fError, fLocator, node.getNodeValue(), xml11Version);            break;        }        case Node.PROCESSING_INSTRUCTION_NODE:{            ProcessingInstruction pinode = (ProcessingInstruction)node ;            String target = pinode.getTarget();            if (verifyNames) {                if (xml11Version) {                    wellformed = XML11Char.isXML11ValidName(target);                } else {                    wellformed = XMLChar.isValidName(target);                }                if (!wellformed) {                    String msg =                        DOMMessageFormatter.formatMessage(                            DOMMessageFormatter.DOM_DOMAIN,                            "wf-invalid-character-in-node-name",                            new Object[] { "Element", node.getNodeName()});                    DOMNormalizer.reportDOMError(                        fErrorHandler,                        fError,                        fLocator,                        msg,                        DOMError.SEVERITY_FATAL_ERROR,                        "wf-invalid-character-in-node-name");                }            }                          DOMNormalizer.isXMLCharWF(fErrorHandler, fError, fLocator, pinode.getData(), xml11Version);            break;        }                }                   }}//DOMSerializerImpl

⌨️ 快捷键说明

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