Java Code Examples for org.w3c.dom.Document#removeChild()
The following examples show how to use
org.w3c.dom.Document#removeChild() .
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: JavaProjectNatureTest.java From netbeans with Apache License 2.0 | 6 votes |
private void upgradeSchemaTestImpl(String from, String to) throws Exception { // Formatting has to be the same as Xerces' formatter produces for this test to pass: String xml1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<java-data xmlns=\""+from+"\">\n" + " <!-- Hello there. -->\n" + " <foo bar=\"baz\" quux=\"whatever\">hello</foo>\n" + " <x>OK</x>\n" + "</java-data>\n"; String xml2expected = xml1.replaceAll(from, to); Document doc1 = XMLUtil.parse(new InputSource(new StringReader(xml1)), false, true, null, null); Element el1 = doc1.getDocumentElement(); Element el2 = LookupProviderImpl.upgradeSchema(el1,to); Document doc2 = XMLUtil.createDocument(JavaProjectNature.EL_JAVA, to, null, null); doc2.removeChild(doc2.getDocumentElement()); doc2.appendChild(doc2.importNode(el2, true)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLUtil.write(doc2, baos, "UTF-8"); String xml2actual = baos.toString("UTF-8").replaceAll(System.getProperty("line.separator"), "\n"); assertEquals("Correct upgrade result", xml2expected, xml2actual); }
Example 2
Source File: XMLLoader.java From ermaster-b with Apache License 2.0 | 6 votes |
public ERDiagram load(InputStream in) throws Exception { DocumentBuilder parser = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document document = parser.parse(in); Node root = document.getFirstChild(); while (root.getNodeType() == Node.COMMENT_NODE) { document.removeChild(root); root = document.getFirstChild(); } load((Element) root); return this.diagram; }
Example 3
Source File: XmlSigOutInterceptor.java From cxf with Apache License 2.0 | 6 votes |
private XMLSignature prepareDetachedSignature(Document doc, String id, String referenceId, String sigAlgo, String digestAlgo) throws Exception { Element docEl = doc.getDocumentElement(); Document newDoc = DOMUtils.createDocument(); doc.removeChild(docEl); newDoc.adoptNode(docEl); docEl.setAttributeNS(null, "Id", id); docEl.setIdAttributeNS(null, "Id", true); Element root = newDoc.createElementNS(envelopeQName.getNamespaceURI(), envelopeQName.getPrefix() + ":" + envelopeQName.getLocalPart()); root.appendChild(docEl); newDoc.appendChild(root); XMLSignature sig = new XMLSignature(newDoc, "", sigAlgo); root.appendChild(sig.getElement()); Transforms transforms = new Transforms(newDoc); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); sig.addDocument(referenceId, transforms, digestAlgo); return sig; }
Example 4
Source File: XmlSigOutInterceptor.java From cxf with Apache License 2.0 | 6 votes |
private XMLSignature prepareEnvelopingSignature(Document doc, String id, String referenceId, String sigAlgo, String digestAlgo) throws Exception { Element docEl = doc.getDocumentElement(); Document newDoc = DOMUtils.createDocument(); doc.removeChild(docEl); newDoc.adoptNode(docEl); Element object = newDoc.createElementNS(Constants.SignatureSpecNS, "ds:Object"); object.appendChild(docEl); docEl.setAttributeNS(null, "Id", id); docEl.setIdAttributeNS(null, "Id", true); XMLSignature sig = new XMLSignature(newDoc, "", sigAlgo); newDoc.appendChild(sig.getElement()); sig.getElement().appendChild(object); Transforms transforms = new Transforms(newDoc); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); sig.addDocument(referenceId, transforms, digestAlgo); return sig; }
Example 5
Source File: WSDiscoveryServiceImpl.java From cxf with Apache License 2.0 | 6 votes |
private Source mapToOld(Document doc, JAXBElement<?> mt) throws JAXBException, XMLStreamException { doc.removeChild(doc.getDocumentElement()); DOMResult result = new DOMResult(doc); XMLStreamWriter r = StaxUtils.createXMLStreamWriter(result); context.createMarshaller().marshal(mt, r); XMLStreamReader domReader = StaxUtils.createXMLStreamReader(doc); Map<String, String> inMap = new HashMap<>(); inMap.put("{" + WSDVersion.INSTANCE_1_1.getNamespace() + "}*", "{" + WSDVersion.INSTANCE_1_0.getNamespace() + "}*"); inMap.put("{" + WSDVersion.INSTANCE_1_1.getAddressingNamespace() + "}*", "{" + WSDVersion.INSTANCE_1_0.getAddressingNamespace() + "}*"); InTransformReader reader = new InTransformReader(domReader, inMap, null, false); doc = StaxUtils.read(reader); return new DOMSource(doc); }
Example 6
Source File: ErmXmlReader.java From erflute with Apache License 2.0 | 6 votes |
public ERDiagram read(InputStream ins) { final Document document; try { final DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); document = parser.parse(ins); } catch (ParserConfigurationException | SAXException | IOException e) { throw new IllegalStateException("failed to read xml.", e); } Node root = document.getFirstChild(); while (root.getNodeType() == Node.COMMENT_NODE) { document.removeChild(root); root = document.getFirstChild(); } load((Element) root); return diagram; }
Example 7
Source File: QuikitServlet.java From attic-polygene-java with Apache License 2.0 | 6 votes |
private void error( Document dom, Throwable exception ) { Element root = dom.getDocumentElement(); dom.removeChild( root ); Element preElement = (Element) dom.appendChild( dom.createElementNS( Page.XHTML, "html" ) ) .appendChild( dom.createElementNS( Page.XHTML, "body" ) ) .appendChild( dom.createElementNS( Page.XHTML, "code" ) ) .appendChild( dom.createElementNS( Page.XHTML, "pre" ) ); StringWriter stringWriter = new StringWriter( 2000 ); PrintWriter writer = new PrintWriter( stringWriter ); exception.printStackTrace( writer ); writer.close(); String content = stringWriter.getBuffer().toString(); preElement.setTextContent( content ); }
Example 8
Source File: WebProjectNatureTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testUpgradeSchema() throws Exception { // Formatting has to be the same as Xerces' formatter produces for this test to pass: String xml1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<web-data xmlns=\"http://www.netbeans.org/ns/freeform-project-web/1\">\n" + " <!-- Hello there. -->\n" + " <foo bar=\"baz\" quux=\"whatever\">hello</foo>\n" + " <x>OK</x>\n" + "</web-data>\n"; String xml2expected = xml1.replaceAll("/1", "/2"); Document doc1 = XMLUtil.parse(new InputSource(new StringReader(xml1)), false, true, null, null); Element el1 = doc1.getDocumentElement(); Element el2 = LookupProviderImpl.upgradeSchema(el1); Document doc2 = XMLUtil.createDocument(WebProjectNature.EL_WEB, WebProjectNature.NS_WEB_2, null, null); doc2.removeChild(doc2.getDocumentElement()); doc2.appendChild(doc2.importNode(el2, true)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLUtil.write(doc2, baos, "UTF-8"); String xml2actual = baos.toString("UTF-8").replaceAll(System.getProperty("line.separator"), "\n"); assertEquals("Correct upgrade result", xml2expected, xml2actual); }
Example 9
Source File: SunEjbJarProxy.java From netbeans with Apache License 2.0 | 5 votes |
private Document removeDocType(Document document){ if (document != null) { org.w3c.dom.Element docElement = document.getDocumentElement(); if (docElement != null) { org.w3c.dom.DocumentType docType = document.getDoctype(); if (docType != null) { document.removeChild(docType); //NOI18N } } } return document; }
Example 10
Source File: SunCmpMappingsProxy.java From netbeans with Apache License 2.0 | 5 votes |
private Document removeDocType(Document document) { if (document != null) { org.w3c.dom.Element docElement = document.getDocumentElement(); if (docElement != null) { org.w3c.dom.DocumentType docType = document.getDoctype(); if (docType != null) { document.removeChild(docType); //NOI18N } } } return document; }
Example 11
Source File: ISD.java From ttt with BSD 2-Clause "Simplified" License | 5 votes |
private static void generateISDWrapper(Document document, TimeInterval interval, TransformerContext context) { Element root = document.getDocumentElement(); Element isd = document.createElementNS(TTMLHelper.NAMESPACE_ISD, "isd"); isd.setAttributeNS(null, "begin", interval.getBegin().toString()); isd.setAttributeNS(null, "end", interval.getEnd().toString()); copyWrapperAttributes(isd, root); copyMiscellaneousAttributes(isd, root); Map<Element, StyleSet> computedStyleSets = generateISDComputedStyleSets(isd, root, context); generateISDRegions(isd, root, computedStyleSets, context); unwrapRedundantAnonymousSpans(isd, root, context); document.removeChild(root); document.appendChild(isd); }
Example 12
Source File: SunApplicationClientProxy.java From netbeans with Apache License 2.0 | 5 votes |
private Document removeDocType(Document document){ if (document != null) { org.w3c.dom.Element docElement = document.getDocumentElement(); if (docElement != null) { org.w3c.dom.DocumentType docType = document.getDoctype(); if (docType != null) { document.removeChild(docType); //NOI18N } } } return document; }
Example 13
Source File: FragmentDialect.java From cxf with Apache License 2.0 | 5 votes |
/** * Helper method. It removes Node and returns its parent. * @param resourceFragment Node to remove. * @return Parent of removed Node. */ private Node removeNode(Node resourceFragment) { Node parent = null; if (resourceFragment.getNodeType() == Node.ATTRIBUTE_NODE) { parent = ((Attr)resourceFragment).getOwnerElement(); } else { parent = resourceFragment.getParentNode(); } if (parent == null) { // resourceFragment is Document Node parent = resourceFragment; } if (resourceFragment.getNodeType() == Node.ATTRIBUTE_NODE) { ((Element)parent).removeAttributeNode((Attr)resourceFragment); } else { if (parent != resourceFragment) { parent.removeChild(resourceFragment); } else { // Both parent and resourceFragment are Document Document doc = (Document) parent; if (doc.getDocumentElement() != null) { doc.removeChild(doc.getDocumentElement()); } } } return parent; }
Example 14
Source File: SamlEnvelopedOutInterceptor.java From cxf with Apache License 2.0 | 5 votes |
private Document createEnvelopedSamlToken(Message message, Document payloadDoc) throws Exception { Element docEl = payloadDoc.getDocumentElement(); SamlAssertionWrapper assertion = SAMLUtils.createAssertion(message); QName rootName = DOMUtils.getElementQName(payloadDoc.getDocumentElement()); if (rootName.equals(envelopeQName)) { docEl.appendChild(assertion.toDOM(payloadDoc)); return payloadDoc; } Document newDoc = DOMUtils.createDocument(); Element root = newDoc.createElementNS(envelopeQName.getNamespaceURI(), envelopeQName.getPrefix() + ":" + envelopeQName.getLocalPart()); newDoc.appendChild(root); Element assertionEl = assertion.toDOM(newDoc); root.appendChild(assertionEl); payloadDoc.removeChild(docEl); newDoc.adoptNode(docEl); root.appendChild(docEl); if (signLater) { // It appears adopting and removing nodes // leaves some stale refs/state with adopted nodes and thus the digest ends up // being wrong on the server side if XML sig is applied later in the enveloped mode // TODO: this is not critical now - but figure out if we can avoid copying // DOMs CachedOutputStream bos = new CachedOutputStream(); StaxUtils.writeTo(newDoc, bos); return StaxUtils.read(bos.getInputStream()); } return newDoc; }
Example 15
Source File: SunWebAppProxy.java From netbeans with Apache License 2.0 | 5 votes |
private Document removeDocType(Document document){ if (document != null) { org.w3c.dom.Element docElement = document.getDocumentElement(); if (docElement != null) { org.w3c.dom.DocumentType docType = document.getDoctype(); if (docType != null) { document.removeChild(docType); //NOI18N } } } return document; }
Example 16
Source File: XMLHelpers.java From cougar with Apache License 2.0 | 5 votes |
public void renameRootElement(Document document, String newRootElementName) { Node rootNode = document.getDocumentElement(); NodeList childNodes = rootNode.getChildNodes(); NamedNodeMap attributes = rootNode.getAttributes(); document.removeChild(rootNode); Node newRootNode = document.createElement(newRootElementName); document.appendChild(newRootNode); int numberOfAttributes = new Integer(attributes.getLength()); for (int i = 0; i < numberOfAttributes; i++) { Attr attributeNode = (Attr)attributes.item(0); Element newRootNodeElement = (Element)newRootNode; Element rootNodeElement = (Element)rootNode; rootNodeElement.removeAttributeNode(attributeNode); newRootNodeElement.setAttributeNode(attributeNode); } int numberOfChildNodes = new Integer(childNodes.getLength()); for (int i = 0; i < numberOfChildNodes; i++) { Node childNode = childNodes.item(0); newRootNode.appendChild(childNode); } }
Example 17
Source File: XMLUtils.java From xcurator with Apache License 2.0 | 5 votes |
public static Document addRoot(Document dataDoc, String elementName) { Element oldRoot = dataDoc.getDocumentElement(); Element newRoot = dataDoc.createElement(elementName); dataDoc.removeChild(oldRoot); newRoot.appendChild(oldRoot); dataDoc.appendChild(newRoot); return dataDoc; }
Example 18
Source File: JavaActionsTest.java From netbeans with Apache License 2.0 | 5 votes |
/** * Format XML as a string. Assumes Xerces serializer in current impl. * Collapse all comments to no body. */ private static String xmlToString(Element el) throws Exception { Document doc = XMLUtil.createDocument("fake", null, null, null); doc.removeChild(doc.getDocumentElement()); doc.appendChild(doc.importNode(el, true)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLUtil.write(doc, baos, "UTF-8"); return baos.toString("UTF-8").replaceAll("<!--([^-]|-[^-])*-->", "<!---->").replaceAll(System.getProperty("line.separator"), "\n"); }
Example 19
Source File: XMLLoader.java From ermasterr with Apache License 2.0 | 4 votes |
public ERDiagram load(final InputStream in, final File file) throws Exception { final DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); final Document document = parser.parse(in); Node root = document.getFirstChild(); while (root.getNodeType() == Node.COMMENT_NODE) { document.removeChild(root); root = document.getFirstChild(); } load((Element) root, file); return diagram; }
Example 20
Source File: cfXmlData.java From openbd-core with GNU General Public License v3.0 | 4 votes |
/** * Parses and potentially validates a xml document using the specified * ValidatorSource. The InputSourceGenerator produces InputSource objects that wrap * the xml document. The ValiatorSource wraps the validation object (DTD/Schema). * Returns a parsed and potentially validated cfXmlData instance. * Note, because DTD validation occurs during parsing, and xml schema validation takes * place after parsing, we need to separate the validation types into two steps. * Also note, if a customHandler is specified, it may not throw any parse or * validation errors/warnings. Which could lead to a null Document being returned. * * @param xs * generator that creates new InputSource instances * @param validator * wrapper for the validation object (DTD/Schema) * @param customHandler * custom ErrorHandler, may be null * @return parsed and potentially validated xml object, or null * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ protected static Document parseXml(XmlSource xs, ValidatorSource validator, ErrorHandler customHandler) throws IOException, SAXException, ParserConfigurationException { InputSource is = null; boolean schemaValidationRequired = false; boolean dtdRemovalRequired = false; EntityResolver dtdResolver = null; DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); fact.setNamespaceAware(true); fact.setIgnoringElementContentWhitespace(true); if (validator.isNull()) { // Return empty content for all entity references (presumably from a <!DOCTYPE ...> // element) so the parser will parse without any DTD validation and not complain when // resolving <!DOCTYPE ...> entity references (if it exists). is = new ValidationInputSource(xs, ValidationInputSource.NO_CHANGE); dtdResolver = new NoValidationResolver(); } else if (validator.isSchema()) { // Return empty content for all entity references (presumably from a <!DOCTYPE ...> // element) so the parser will parse without any DTD validation and not complain when // resolving <!DOCTYPE ...> entity references (if it exists). is = new ValidationInputSource(xs, ValidationInputSource.NO_CHANGE); dtdResolver = new NoValidationResolver(); // Note that we must do some post parse xml schema validation. schemaValidationRequired = true; } else if (validator.isEmptyString() && !xs.hasDTD()) { // Return empty content for all entity references (presumably from a <!DOCTYPE ...> // element) so the parser will parse without any DTD validation and not complain when // resolving <!DOCTYPE ...> entity references (if it exists). is = new ValidationInputSource(xs, ValidationInputSource.NO_CHANGE); dtdResolver = new NoValidationResolver(); // Note that we must do some post parse xml schema validation. This assumes // that the xml doc has some embedded xml schema reference. schemaValidationRequired = true; } else if (validator.isEmptyString()) { // Best have DTD referenced in the xml source. Set DTD validation to true, // leave the existing <!DOCTYPE ...> element intact. fact.setValidating(true); if (customHandler == null) customHandler = new ValidationErrorHandler(); is = new ValidationInputSource(xs, ValidationInputSource.NO_CHANGE); } else { // Must have specified a DTD validator object so set DTD validation // to true, read the <!DOCTYPE ...> element while parsing and return // the specified DTD validator during entity reference lookup, or if // no <!DOCTYPE ..> element exists, add our own so we can return the // specified DTD validator content during entity reference lookup. fact.setValidating(true); if (customHandler == null) customHandler = new ValidationErrorHandler(); dtdRemovalRequired = !xs.hasDTD(); ValidationResolver vr = new ValidationResolver(validator); dtdResolver = vr; is = new ValidationInputSource(xs, vr, ValidationInputSource.READ_ADD); } DocumentBuilder parser = fact.newDocumentBuilder(); parser.setEntityResolver(dtdResolver); // if these are null, it doesn't matter, parser.setErrorHandler(customHandler); // setting these won't change default behavior Document doc = parser.parse(is); if (doc != null) { doc.normalize(); // Now see if we need to do any schema validation if (schemaValidationRequired) validateXml(doc, validator, customHandler); } // Remove the inserted DTD (if necessary) if (doc != null && dtdRemovalRequired && doc.getDoctype() != null) doc.removeChild(doc.getDoctype()); // Return the parsed (and possibly validated Document) return doc; }