Java Code Examples for org.w3c.dom.Node#DOCUMENT_NODE
The following examples show how to use
org.w3c.dom.Node#DOCUMENT_NODE .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DOMResultBuilder.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
public void setDOMResult(DOMResult result) { fCurrentNode = null; fFragmentRoot = null; fIgnoreChars = false; fTargetChildren.clear(); if (result != null) { fTarget = result.getNode(); fNextSibling = result.getNextSibling(); fDocument = (fTarget.getNodeType() == Node.DOCUMENT_NODE) ? (Document) fTarget : fTarget.getOwnerDocument(); fDocumentImpl = (fDocument instanceof CoreDocumentImpl) ? (CoreDocumentImpl) fDocument : null; fStorePSVI = (fDocument instanceof PSVIDocumentImpl); return; } fTarget = null; fNextSibling = null; fDocument = null; fDocumentImpl = null; fStorePSVI = false; }
Example 2
Source File: UnmarshallerImpl.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public final Object unmarshal0( Node node, JaxBeanInfo expectedType ) throws JAXBException { try { final DOMScanner scanner = new DOMScanner(); InterningXmlVisitor handler = new InterningXmlVisitor(createUnmarshallerHandler(null,false,expectedType)); scanner.setContentHandler(new SAXConnector(handler,scanner)); if(node.getNodeType() == Node.ELEMENT_NODE) { scanner.scan((Element)node); } else if(node.getNodeType() == Node.DOCUMENT_NODE) { scanner.scan((Document)node); } else { throw new IllegalArgumentException("Unexpected node type: "+node); } Object retVal = handler.getContext().getResult(); handler.getContext().clearResult(); return retVal; } catch( SAXException e ) { throw createUnmarshalException(e); } }
Example 3
Source File: DOM3TreeWalker.java From j2objc with Apache License 2.0 | 6 votes |
/** * End processing of given node * * * @param node Node we just finished processing * * @throws org.xml.sax.SAXException */ protected void endNode(Node node) throws org.xml.sax.SAXException { switch (node.getNodeType()) { case Node.DOCUMENT_NODE : break; case Node.DOCUMENT_TYPE_NODE : serializeDocType((DocumentType) node, false); break; case Node.ELEMENT_NODE : serializeElement((Element) node, false); break; case Node.CDATA_SECTION_NODE : break; case Node.ENTITY_REFERENCE_NODE : serializeEntityReference((EntityReference) node, false); break; default : } }
Example 4
Source File: Xml.java From RADL with Apache License 2.0 | 6 votes |
private static void append(Node node, int indentationLevel, Map<String, String> namespaces, StringBuilder builder) { switch (node.getNodeType()) { case Node.DOCUMENT_NODE: appendDocument(node, indentationLevel, namespaces, builder); break; case Node.ELEMENT_NODE: appendElement(node, indentationLevel, namespaces, builder); break; case Node.ATTRIBUTE_NODE: appendAttribute(node, namespaces, builder); break; case Node.TEXT_NODE: appendText(node, builder); break; case Node.COMMENT_NODE: appendComment(node, indentationLevel, builder); break; default: throw new UnsupportedOperationException("Unhandled node type: " + node.getNodeType()); } }
Example 5
Source File: XPathAPI.java From Bytecoder with Apache License 2.0 | 5 votes |
/** * Evaluate XPath string to an XObject. * XPath namespace prefixes are resolved from the namespaceNode. * The implementation of this is a little slow, since it creates * a number of objects each time it is called. This could be optimized * to keep the same objects around, but then thread-safety issues would arise. * * @param contextNode The node to start searching from. * @param str A valid XPath string. * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. * @see com.sun.org.apache.xpath.internal.objects.XObject * @see com.sun.org.apache.xpath.internal.objects.XNull * @see com.sun.org.apache.xpath.internal.objects.XBoolean * @see com.sun.org.apache.xpath.internal.objects.XNumber * @see com.sun.org.apache.xpath.internal.objects.XString * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag * * @throws TransformerException */ public static XObject eval(Node contextNode, String str, Node namespaceNode) throws TransformerException { // Since we don't have a XML Parser involved here, install some default support // for things like namespaces, etc. // (Changed from: XPathContext xpathSupport = new XPathContext(); // because XPathContext is weak in a number of areas... perhaps // XPathContext should be done away with.) XPathContext xpathSupport = new XPathContext(JdkXmlUtils.OVERRIDE_PARSER_DEFAULT); // Create an object to resolve namespace prefixes. // XPath namespaces are resolved from the input context node's document element // if it is a root node, or else the current context node (for lack of a better // resolution space, given the simplicity of this sample code). PrefixResolverDefault prefixResolver = new PrefixResolverDefault( (namespaceNode.getNodeType() == Node.DOCUMENT_NODE) ? ((Document) namespaceNode).getDocumentElement() : namespaceNode); // Create the XPath object. XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); // Execute the XPath, and have it return the result // return xpath.execute(xpathSupport, contextNode, prefixResolver); int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode); return xpath.execute(xpathSupport, ctxtNode, prefixResolver); }
Example 6
Source File: CachedXPathAPI.java From hottub with GNU General Public License v2.0 | 5 votes |
/** * Evaluate XPath string to an XObject. * XPath namespace prefixes are resolved from the namespaceNode. * The implementation of this is a little slow, since it creates * a number of objects each time it is called. This could be optimized * to keep the same objects around, but then thread-safety issues would arise. * * @param contextNode The node to start searching from. * @param str A valid XPath string. * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. * @see com.sun.org.apache.xpath.internal.objects.XObject * @see com.sun.org.apache.xpath.internal.objects.XNull * @see com.sun.org.apache.xpath.internal.objects.XBoolean * @see com.sun.org.apache.xpath.internal.objects.XNumber * @see com.sun.org.apache.xpath.internal.objects.XString * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag * * @throws TransformerException */ public XObject eval(Node contextNode, String str, Node namespaceNode) throws TransformerException { // Since we don't have a XML Parser involved here, install some default support // for things like namespaces, etc. // (Changed from: XPathContext xpathSupport = new XPathContext(); // because XPathContext is weak in a number of areas... perhaps // XPathContext should be done away with.) // Create an object to resolve namespace prefixes. // XPath namespaces are resolved from the input context node's document element // if it is a root node, or else the current context node (for lack of a better // resolution space, given the simplicity of this sample code). PrefixResolverDefault prefixResolver = new PrefixResolverDefault( (namespaceNode.getNodeType() == Node.DOCUMENT_NODE) ? ((Document) namespaceNode).getDocumentElement() : namespaceNode); // Create the XPath object. XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); // Execute the XPath, and have it return the result // return xpath.execute(xpathSupport, contextNode, prefixResolver); int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode); return xpath.execute(xpathSupport, ctxtNode, prefixResolver); }
Example 7
Source File: DOMResultAugmentor.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
public void setDOMResult(DOMResult result) { fIgnoreChars = false; if (result != null) { final Node target = result.getNode(); fDocument = (target.getNodeType() == Node.DOCUMENT_NODE) ? (Document) target : target.getOwnerDocument(); fDocumentImpl = (fDocument instanceof CoreDocumentImpl) ? (CoreDocumentImpl) fDocument : null; fStorePSVI = (fDocument instanceof PSVIDocumentImpl); return; } fDocument = null; fDocumentImpl = null; fStorePSVI = false; }
Example 8
Source File: DOM2DTM.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * Returns the <code>Element</code> whose <code>ID</code> is given by * <code>elementId</code>. If no such element exists, returns * <code>DTM.NULL</code>. Behavior is not defined if more than one element * has this <code>ID</code>. Attributes (including those * with the name "ID") are not of type ID unless so defined by DTD/Schema * information available to the DTM implementation. * Implementations that do not know whether attributes are of type ID or * not are expected to return <code>DTM.NULL</code>. * * <p>%REVIEW% Presumably IDs are still scoped to a single document, * and this operation searches only within a single document, right? * Wouldn't want collisions between DTMs in the same process.</p> * * @param elementId The unique <code>id</code> value for an element. * @return The handle of the matching element. */ public int getElementById(String elementId) { Document doc = (m_root.getNodeType() == Node.DOCUMENT_NODE) ? (Document) m_root : m_root.getOwnerDocument(); if(null != doc) { Node elem = doc.getElementById(elementId); if(null != elem) { int elemHandle = getHandleFromNode(elem); if(DTM.NULL == elemHandle) { int identity = m_nodes.size()-1; while (DTM.NULL != (identity = getNextNodeIdentity(identity))) { Node node = getNode(identity); if(node == elem) { elemHandle = getHandleFromNode(elem); break; } } } return elemHandle; } } return DTM.NULL; }
Example 9
Source File: DOMUtils.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
/** * Returns the owner document of the specified node. * * @param node the node * @return the owner document */ public static Document getOwnerDocument(Node node) { if (node.getNodeType() == Node.DOCUMENT_NODE) { return (Document)node; } else { return node.getOwnerDocument(); } }
Example 10
Source File: Dom.java From caja with Apache License 2.0 | 5 votes |
/** * Create a Dom object containing a DocumentFragment containing the provided * node. * * If the provided node is a Document, transplant its root node. If the * provided node is a DocumentFragment, use it rather than creating a new * fragment. */ public static Dom transplant(Node node) { if (node.getNodeType() == Node.DOCUMENT_NODE) { node = ((Document) node).getDocumentElement(); } else if (node.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) { return new Dom((DocumentFragment) node); } DocumentFragment f = node.getOwnerDocument().createDocumentFragment(); f.appendChild(node); Nodes.setFilePositionFor(f, Nodes.getFilePositionFor(node)); return new Dom(f); }
Example 11
Source File: DomTreeWalker.java From HtmlUnit-Android with Apache License 2.0 | 5 votes |
/** * Given a {@link Node}, return the appropriate constant for whatToShow. * * @param node the node * @return the whatToShow constant for the type of specified node */ static int getFlagForNode(final Node node) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: return NodeFilter.SHOW_ELEMENT; case Node.ATTRIBUTE_NODE: return NodeFilter.SHOW_ATTRIBUTE; case Node.TEXT_NODE: return NodeFilter.SHOW_TEXT; case Node.CDATA_SECTION_NODE: return NodeFilter.SHOW_CDATA_SECTION; case Node.ENTITY_REFERENCE_NODE: return NodeFilter.SHOW_ENTITY_REFERENCE; case Node.ENTITY_NODE: return NodeFilter.SHOW_ENTITY; case Node.PROCESSING_INSTRUCTION_NODE: return NodeFilter.SHOW_PROCESSING_INSTRUCTION; case Node.COMMENT_NODE: return NodeFilter.SHOW_COMMENT; case Node.DOCUMENT_NODE: return NodeFilter.SHOW_DOCUMENT; case Node.DOCUMENT_TYPE_NODE: return NodeFilter.SHOW_DOCUMENT_TYPE; case Node.DOCUMENT_FRAGMENT_NODE: return NodeFilter.SHOW_DOCUMENT_FRAGMENT; case Node.NOTATION_NODE: return NodeFilter.SHOW_NOTATION; default: return 0; } }
Example 12
Source File: XMLDOMWriterImpl.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * Internal current Node pointer will point to the parent of the current Node. * @throws javax.xml.stream.XMLStreamException {@inheritDoc} */ public void writeEndElement() throws XMLStreamException { Node node= currentNode.getParentNode(); if(currentNode.getNodeType() == Node.DOCUMENT_NODE){ currentNode = null; }else{ currentNode = node; } if(needContextPop[depth]){ needContextPop[depth] = false; namespaceContext.popContext(); } depth--; }
Example 13
Source File: DOMPrinter.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
public void print(Node node) throws XMLStreamException { switch (node.getNodeType()) { case Node.DOCUMENT_NODE: visitDocument((Document) node); break; case Node.DOCUMENT_FRAGMENT_NODE: visitDocumentFragment((DocumentFragment) node); break; case Node.ELEMENT_NODE: visitElement((Element) node); break; case Node.TEXT_NODE: visitText((Text) node); break; case Node.CDATA_SECTION_NODE: visitCDATASection((CDATASection) node); break; case Node.PROCESSING_INSTRUCTION_NODE: visitProcessingInstruction((ProcessingInstruction) node); break; case Node.ENTITY_REFERENCE_NODE: visitReference((EntityReference) node); break; case Node.COMMENT_NODE: visitComment((Comment) node); break; case Node.DOCUMENT_TYPE_NODE: break; case Node.ATTRIBUTE_NODE: case Node.ENTITY_NODE: default: throw new XMLStreamException("Unexpected DOM Node Type " + node.getNodeType() ); } }
Example 14
Source File: XmlUtil.java From sakai with Educational Community License v2.0 | 4 votes |
/** * Get a textual representation of a Node. * @param node The Node * @return the document in a text string */ public static String getDOMString(Node node) { //String domString = ""; StringBuilder domStringbuf = new StringBuilder(); int type = node.getNodeType(); switch (type) { // print the document element case Node.DOCUMENT_NODE: { domStringbuf.append("<?xml version=\"1.0\" ?>\n"); domStringbuf.append(getDOMString(((Document)node).getDocumentElement())); break; } // print element with attributes case Node.ELEMENT_NODE: { domStringbuf.append("<"); domStringbuf.append(node.getNodeName()); NamedNodeMap attrs = node.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); //domString += (" " + attr.getNodeName().trim() + // "=\"" + attr.getNodeValue().trim() + // "\""); domStringbuf.append((" " + attr.getNodeName().trim() + "=\"" + attr.getNodeValue().trim() + "\"")); } //domString = domStringbuf.toString(); domStringbuf.append(">"); NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) domStringbuf.append(getDOMString(children.item(i))); } domStringbuf.append("</"); domStringbuf.append(node.getNodeName()); domStringbuf.append(">\n"); break; } // handle entity reference nodes case Node.ENTITY_REFERENCE_NODE: { domStringbuf.append("&"); domStringbuf.append(node.getNodeName().trim()); domStringbuf.append(";"); break; } // print cdata sections case Node.CDATA_SECTION_NODE: { domStringbuf.append(""); break; } // print text case Node.TEXT_NODE: { String val = node.getNodeValue(); if (val==null) val = ""; domStringbuf.append(val);//rshastri .trim() removed SAK-1671 break; } // print processing instruction case Node.PROCESSING_INSTRUCTION_NODE: { domStringbuf.append(""); break; } } if (type == Node.ELEMENT_NODE) { domStringbuf.append("\n"); } String domString = domStringbuf.toString(); return domString; }
Example 15
Source File: RangeImpl.java From Bytecoder with Apache License 2.0 | 4 votes |
public void insertNode(Node newNode) throws DOMException, RangeException { if ( newNode == null ) return; //throw exception? int type = newNode.getNodeType(); if (fDocument.errorChecking) { if (fDetach) { throw new DOMException( DOMException.INVALID_STATE_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_STATE_ERR", null)); } if ( fDocument != newNode.getOwnerDocument() ) { throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null)); } if (type == Node.ATTRIBUTE_NODE || type == Node.ENTITY_NODE || type == Node.NOTATION_NODE || type == Node.DOCUMENT_NODE) { throw new RangeExceptionImpl( RangeException.INVALID_NODE_TYPE_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_NODE_TYPE_ERR", null)); } } Node cloneCurrent; Node current; int currentChildren = 0; fInsertedFromRange = true; //boolean MULTIPLE_MODE = false; if (fStartContainer.getNodeType() == Node.TEXT_NODE) { Node parent = fStartContainer.getParentNode(); currentChildren = parent.getChildNodes().getLength(); //holds number of kids before insertion // split text node: results is 3 nodes.. cloneCurrent = fStartContainer.cloneNode(false); ((TextImpl)cloneCurrent).setNodeValueInternal( (cloneCurrent.getNodeValue()).substring(fStartOffset)); ((TextImpl)fStartContainer).setNodeValueInternal( (fStartContainer.getNodeValue()).substring(0,fStartOffset)); Node next = fStartContainer.getNextSibling(); if (next != null) { if (parent != null) { parent.insertBefore(newNode, next); parent.insertBefore(cloneCurrent, next); } } else { if (parent != null) { parent.appendChild(newNode); parent.appendChild(cloneCurrent); } } //update ranges after the insertion if ( fEndContainer == fStartContainer) { fEndContainer = cloneCurrent; //endContainer is the new Node created fEndOffset -= fStartOffset; } else if ( fEndContainer == parent ) { //endContainer was not a text Node. //endOffset + = number_of_children_added fEndOffset += (parent.getChildNodes().getLength() - currentChildren); } // signal other Ranges to update their start/end containers/offsets signalSplitData(fStartContainer, cloneCurrent, fStartOffset); } else { // ! TEXT_NODE if ( fEndContainer == fStartContainer ) //need to remember number of kids currentChildren= fEndContainer.getChildNodes().getLength(); current = fStartContainer.getFirstChild(); int i = 0; for(i = 0; i < fStartOffset && current != null; i++) { current=current.getNextSibling(); } if (current != null) { fStartContainer.insertBefore(newNode, current); } else { fStartContainer.appendChild(newNode); } //update fEndOffset. ex:<body><p/></body>. Range(start;end): body,0; body,1 // insert <h1>: <body></h1><p/></body>. Range(start;end): body,0; body,2 if ( fEndContainer == fStartContainer && fEndOffset != 0 ) { //update fEndOffset if not 0 fEndOffset += (fEndContainer.getChildNodes().getLength() - currentChildren); } } fInsertedFromRange = false; }
Example 16
Source File: DOMSubTreeData.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
/** * Recursively traverses the subtree, and returns an XPath-equivalent * node-set of all nodes traversed, excluding any comment nodes, * if specified. * * @param node the node to traverse * @param nodeSet the set of nodes traversed so far * @param the previous sibling node */ @SuppressWarnings("fallthrough") private void nodeSetMinusCommentNodes(Node node, List<Node> nodeSet, Node prevSibling) { switch (node.getNodeType()) { case Node.ELEMENT_NODE : NamedNodeMap attrs = node.getAttributes(); if (attrs != null) { for (int i = 0, len = attrs.getLength(); i < len; i++) { nodeSet.add(attrs.item(i)); } } nodeSet.add(node); Node pSibling = null; for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { nodeSetMinusCommentNodes(child, nodeSet, pSibling); pSibling = child; } break; case Node.DOCUMENT_NODE : pSibling = null; for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { nodeSetMinusCommentNodes(child, nodeSet, pSibling); pSibling = child; } break; case Node.TEXT_NODE : case Node.CDATA_SECTION_NODE: // emulate XPath which only returns the first node in // contiguous text/cdata nodes if (prevSibling != null && (prevSibling.getNodeType() == Node.TEXT_NODE || prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)) { return; } nodeSet.add(node); break; case Node.PROCESSING_INSTRUCTION_NODE : nodeSet.add(node); break; case Node.COMMENT_NODE: if (withComments) { nodeSet.add(node); } } }
Example 17
Source File: TreeWalker.java From openjdk-8-source with GNU General Public License v2.0 | 4 votes |
/** * End processing of given node * * * @param node Node we just finished processing * * @throws org.xml.sax.SAXException */ protected void endNode(Node node) throws org.xml.sax.SAXException { switch (node.getNodeType()) { case Node.DOCUMENT_NODE : break; case Node.ELEMENT_NODE : String ns = m_dh.getNamespaceOfNode(node); if(null == ns) ns = ""; this.m_contentHandler.endElement(ns, m_dh.getLocalNameOfNode(node), node.getNodeName()); NamedNodeMap atts = ((Element) node).getAttributes(); int nAttrs = atts.getLength(); for (int i = 0; i < nAttrs; i++) { Node attr = atts.item(i); String attrName = attr.getNodeName(); if (attrName.equals("xmlns") || attrName.startsWith("xmlns:")) { int index; // Use "" instead of null, as Xerces likes "" for the // name of the default namespace. Fix attributed // to "Steven Murray" <[email protected]>. String prefix = (index = attrName.indexOf(":")) < 0 ? "" : attrName.substring(index + 1); this.m_contentHandler.endPrefixMapping(prefix); } } break; case Node.CDATA_SECTION_NODE : break; case Node.ENTITY_REFERENCE_NODE : { EntityReference eref = (EntityReference) node; if (m_contentHandler instanceof LexicalHandler) { LexicalHandler lh = ((LexicalHandler) this.m_contentHandler); lh.endEntity(eref.getNodeName()); } } break; default : } }
Example 18
Source File: RangeImpl.java From openjdk-8 with GNU General Public License v2.0 | 4 votes |
public void insertNode(Node newNode) throws DOMException, RangeException { if ( newNode == null ) return; //throw exception? int type = newNode.getNodeType(); if (fDocument.errorChecking) { if (fDetach) { throw new DOMException( DOMException.INVALID_STATE_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_STATE_ERR", null)); } if ( fDocument != newNode.getOwnerDocument() ) { throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null)); } if (type == Node.ATTRIBUTE_NODE || type == Node.ENTITY_NODE || type == Node.NOTATION_NODE || type == Node.DOCUMENT_NODE) { throw new RangeExceptionImpl( RangeException.INVALID_NODE_TYPE_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_NODE_TYPE_ERR", null)); } } Node cloneCurrent; Node current; int currentChildren = 0; fInsertedFromRange = true; //boolean MULTIPLE_MODE = false; if (fStartContainer.getNodeType() == Node.TEXT_NODE) { Node parent = fStartContainer.getParentNode(); currentChildren = parent.getChildNodes().getLength(); //holds number of kids before insertion // split text node: results is 3 nodes.. cloneCurrent = fStartContainer.cloneNode(false); ((TextImpl)cloneCurrent).setNodeValueInternal( (cloneCurrent.getNodeValue()).substring(fStartOffset)); ((TextImpl)fStartContainer).setNodeValueInternal( (fStartContainer.getNodeValue()).substring(0,fStartOffset)); Node next = fStartContainer.getNextSibling(); if (next != null) { if (parent != null) { parent.insertBefore(newNode, next); parent.insertBefore(cloneCurrent, next); } } else { if (parent != null) { parent.appendChild(newNode); parent.appendChild(cloneCurrent); } } //update ranges after the insertion if ( fEndContainer == fStartContainer) { fEndContainer = cloneCurrent; //endContainer is the new Node created fEndOffset -= fStartOffset; } else if ( fEndContainer == parent ) { //endContainer was not a text Node. //endOffset + = number_of_children_added fEndOffset += (parent.getChildNodes().getLength() - currentChildren); } // signal other Ranges to update their start/end containers/offsets signalSplitData(fStartContainer, cloneCurrent, fStartOffset); } else { // ! TEXT_NODE if ( fEndContainer == fStartContainer ) //need to remember number of kids currentChildren= fEndContainer.getChildNodes().getLength(); current = fStartContainer.getFirstChild(); int i = 0; for(i = 0; i < fStartOffset && current != null; i++) { current=current.getNextSibling(); } if (current != null) { fStartContainer.insertBefore(newNode, current); } else { fStartContainer.appendChild(newNode); } //update fEndOffset. ex:<body><p/></body>. Range(start;end): body,0; body,1 // insert <h1>: <body></h1><p/></body>. Range(start;end): body,0; body,2 if ( fEndContainer == fStartContainer && fEndOffset != 0 ) { //update fEndOffset if not 0 fEndOffset += (fEndContainer.getChildNodes().getLength() - currentChildren); } } fInsertedFromRange = false; }
Example 19
Source File: ManifestMerger.java From javaide with GNU General Public License v3.0 | 4 votes |
private static int insertSourceMarker(@NonNull Node parent, @NonNull Node node, @NonNull File file, boolean after) { int insertCount = 0; Document doc = parent.getNodeType() == Node.DOCUMENT_NODE ? (Document) parent : parent.getOwnerDocument(); String comment; try { comment = SdkUtils.createPathComment(file, true); } catch (MalformedURLException e) { return insertCount; } Node prev = node.getPreviousSibling(); String newline; if (prev != null && prev.getNodeType() == Node.TEXT_NODE) { // Duplicate indentation from previous line. Once we switch the merger // over to using the XmlPrettyPrinter, we won't need this. newline = prev.getNodeValue(); int index = newline.lastIndexOf('\n'); if (index != -1) { newline = newline.substring(index); } } else { newline = "\n"; } if (after) { node = node.getNextSibling(); } parent.insertBefore(doc.createComment(comment), node); insertCount++; // Can't add text nodes at the document level in Xerces, even though // it will happily parse these if (parent.getNodeType() != Node.DOCUMENT_NODE) { parent.insertBefore(doc.createTextNode(newline), node); insertCount++; } return insertCount; }
Example 20
Source File: DOMSerializerImpl.java From jdk8u60 with GNU General Public License v2.0 | 4 votes |
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); } } }