domserializerimpl.java

来自「JAVA 所有包」· Java 代码 · 共 1,212 行 · 第 1/4 页

JAVA
1,212
字号
            // 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, (Object[]) 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, (Object[]) 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"))) {                out = new FileOutputStream(getPathWithoutEscapes(url.getFile()));                        }            // 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 if (node.getNodeType() == Node.TEXT_NODE ||                     node.getNodeType() == Node.COMMENT_NODE ||                    node.getNodeType() == Node.ENTITY_REFERENCE_NODE ||                    node.getNodeType() == Node.CDATA_SECTION_NODE ||                    node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE ) {                ser.serialize(node);            }            else                return false;        } catch (LSException lse) {            // Rethrow LSException.            throw lse;        } 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.fNamespacePrefixes = (features & NSDECL) != 0;        ser._format.setOmitComments((features & COMMENTS)==0);        ser._format.setOmitXMLDeclaration((features & XMLDECL) == 0);           ser._format.setIndenting((features & FORMAT_PRETTY_PRINT) != 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, (Object[]) null)).booleanValue();                }            } catch (Exception e) {                //no way to test the version...                //ignore the exception            }            if (node.getFirstChild() != null) {                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;                }            }            else {                verify(node, verifyNames, false);            }        }    }            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");                                }                                                    }                                           }                }                                NamedNodeMap attributes = (node.hasAttributes()) ? 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, 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;        }                }                   }        private String getPathWithoutEscapes(String origPath) {        if (origPath != null && origPath.length() != 0 && origPath.indexOf('%') != -1) {            // Locate the escape characters            StringTokenizer tokenizer = new StringTokenizer(origPath, "%");            StringBuffer result = new StringBuffer(origPath.length());            int size = tokenizer.countTokens();            result.append(tokenizer.nextToken());            for(int i = 1; i < size; ++i) {                String token = tokenizer.nextToken();                // Decode the 2 digit hexadecimal number following % in '%nn'                result.append((char)Integer.valueOf(token.substring(0, 2), 16).intValue());                result.append(token.substring(2));            }            return result.toString();        }        return origPath;    }}//DOMSerializerImpl

⌨️ 快捷键说明

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