List of usage examples for org.w3c.dom Node cloneNode
public Node cloneNode(boolean deep);
From source file:Main.java
/** * Clone given Node into target Document. If targe is null, same Document will be used. * If deep is specified, all children below will also be cloned. *//*from w w w. j a va 2 s.com*/ public final static Node cloneNode(Node node, Document target, boolean deep) throws DOMException { if ((target == null) || (node.getOwnerDocument() == target)) { // same Document return node.cloneNode(deep); } else { //DOM level 2 provides this in Document, so once xalan switches to that, //we can take out all the below and just call target.importNode(node, deep); //For now, we implement based on the javadocs for importNode Node newNode; int nodeType = node.getNodeType(); switch (nodeType) { case Node.ATTRIBUTE_NODE: newNode = target.createAttribute(node.getNodeName()); break; case Node.DOCUMENT_FRAGMENT_NODE: newNode = target.createDocumentFragment(); break; case Node.ELEMENT_NODE: Element newElement = target.createElement(node.getNodeName()); NamedNodeMap nodeAttr = node.getAttributes(); if (nodeAttr != null) { for (int i = 0; i < nodeAttr.getLength(); i++) { Attr attr = (Attr) nodeAttr.item(i); if (attr.getSpecified()) { Attr newAttr = (Attr) cloneNode(attr, target, true); newElement.setAttributeNode(newAttr); } } } newNode = newElement; break; case Node.ENTITY_REFERENCE_NODE: newNode = target.createEntityReference(node.getNodeName()); break; case Node.PROCESSING_INSTRUCTION_NODE: newNode = target.createProcessingInstruction(node.getNodeName(), node.getNodeValue()); break; case Node.TEXT_NODE: newNode = target.createTextNode(node.getNodeValue()); break; case Node.CDATA_SECTION_NODE: newNode = target.createCDATASection(node.getNodeValue()); break; case Node.COMMENT_NODE: newNode = target.createComment(node.getNodeValue()); break; case Node.NOTATION_NODE: case Node.ENTITY_NODE: case Node.DOCUMENT_TYPE_NODE: case Node.DOCUMENT_NODE: default: throw new IllegalArgumentException("Importing of " + node + " not supported yet"); } if (deep) { for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { newNode.appendChild(cloneNode(child, target, true)); } } return newNode; } }
From source file:de.ingrid.interfaces.csw.domain.encoding.impl.XMLEncoding.java
protected static Document extractFromDocument(Node node) throws Exception { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true);/*from ww w . j a va2 s .c o m*/ DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.newDocument(); Node copy = node.cloneNode(true); Node adopted = doc.adoptNode(copy); doc.appendChild(adopted); return doc; }
From source file:com.ephesoft.dcma.util.OCREngineUtil.java
/** * To format HOCR for Tesseract./*w ww. j a v a 2 s. c o m*/ * @param outputFilePath {@link String} * @param actualFolderLocation {@link String} * @param pageId {@link String} * @throws XPathExpressionException if error occurs * @throws TransformerException if error occurs * @throws IOException if error occurs */ public static void formatHOCRForTesseract(final String outputFilePath, final String actualFolderLocation, final String pageId) throws XPathExpressionException, TransformerException, IOException { LOGGER.info("Entering format HOCR for tessearct . outputfilepath : " + outputFilePath); InputStream inputStream = new FileInputStream(outputFilePath); XPathFactory xFactory = new org.apache.xpath.jaxp.XPathFactoryImpl(); XPath xpath = xFactory.newXPath(); XPathExpression pageExpr = xpath.compile("//div[@class=\"ocr_page\"]"); XPathExpression wordExpr = xpath.compile("//span[@class=\"ocr_word\"]"); // Output format supported by Tesseract 3.00 XPathExpression xOcrWordExpr = xpath.compile("//span[@class=\"xocr_word\"]"); // Output format supported by Tesseract 3.01 XPathExpression ocrXWordExpr = xpath.compile("//span[@class=\"ocrx_word\"]"); org.w3c.dom.Document doc2 = null; try { doc2 = XMLUtil.createDocumentFrom(inputStream); } catch (Exception e) { LOGGER.info("Premature end of file for " + outputFilePath + e); } finally { IOUtils.closeQuietly(inputStream); } if (doc2 != null) { LOGGER.info("document is not null."); NodeList wordList = (NodeList) wordExpr.evaluate(doc2, XPathConstants.NODESET); for (int wordNodeIndex = 0; wordNodeIndex < wordList.getLength(); wordNodeIndex++) { setWordNodeTextContent(xOcrWordExpr, ocrXWordExpr, wordList, wordNodeIndex); } NodeList pageList = (NodeList) pageExpr.evaluate(doc2, XPathConstants.NODESET); for (int pageNodeIndex = 0; pageNodeIndex < pageList.getLength(); pageNodeIndex++) { Node pageNode = pageList.item(pageNodeIndex); if (pageNode != null && ((Node) pageNode.getAttributes().getNamedItem(UtilConstants.ID_ATTR)) != null) { String pageID = ((Node) pageNode.getAttributes().getNamedItem(UtilConstants.ID_ATTR)) .getTextContent(); wordExpr = xpath.compile("//div[@id='" + pageID + "']//span[@class='ocr_word']"); NodeList wordInPageList = (NodeList) wordExpr.evaluate(pageNode, XPathConstants.NODESET); Node pageNodeClone = pageNode.cloneNode(false); for (int i = 0; i < wordInPageList.getLength(); i++) { pageNodeClone.appendChild(wordInPageList.item(i)); } pageNode.getParentNode().appendChild(pageNodeClone); pageNode.getParentNode().removeChild(pageNode); } } XMLUtil.flushDocumentToFile(doc2.getDocumentElement().getOwnerDocument(), outputFilePath); File tempFile = new File(actualFolderLocation + File.separator + pageId + "_tempFile_hocr.html"); FileUtils.copyFile(new File(outputFilePath), tempFile); XMLUtil.htmlOutputStream(tempFile.getAbsolutePath(), outputFilePath); boolean isTempFileDeleted = tempFile.delete(); if (!isTempFileDeleted) { tempFile.delete(); } } LOGGER.info("Exiting format HOCR for tessearct . outputfilepath : " + outputFilePath); }
From source file:Main.java
/** * Copy elements from one document to another attaching at the specified * element and translating the namespace. * * @param from copy the children of this element (exclusive) * @param to where to attach the copied elements * @param newNamespace destination namespace * * @since 8.4/*from w w w . ja va2s.c om*/ */ public static void copyDocument(Element from, Element to, String newNamespace) { Document doc = to.getOwnerDocument(); NodeList nl = from.getChildNodes(); int length = nl.getLength(); for (int i = 0; i < length; i++) { Node node = nl.item(i); Node newNode = null; if (Node.ELEMENT_NODE == node.getNodeType()) { Element oldElement = (Element) node; newNode = doc.createElementNS(newNamespace, oldElement.getTagName()); NamedNodeMap m = oldElement.getAttributes(); Element newElement = (Element) newNode; for (int index = 0; index < m.getLength(); index++) { Node attr = m.item(index); newElement.setAttribute(attr.getNodeName(), attr.getNodeValue()); } copyDocument(oldElement, newElement, newNamespace); } else { newNode = node.cloneNode(true); newNode = to.getOwnerDocument().importNode(newNode, true); } if (newNode != null) { to.appendChild(newNode); } } }
From source file:de.betterform.xml.dom.DOMUtil.java
/** * This is a workaround for very strange behaviour of xerces-1.4.2 DOM importNode. *///from w ww. jav a2 s . com public static Node importNode(Document document, Node toImport) { if (toImport != null) { Node root = toImport.cloneNode(false); // no deep cloning! root = document.importNode(root, false); for (Node n = toImport.getFirstChild(); n != null; n = n.getNextSibling()) { root.appendChild(document.importNode(n, true)); } return root; } return null; }
From source file:Main.java
private static Node convertFromNamespaceForm(final Node node) { if (node instanceof Element) { final Document document = node.getOwnerDocument(); final Element newElement = document.createElementNS(null, node.getLocalName()); final NodeList children = node.getChildNodes(); for (int i = 0, n = children.getLength(); i < n; i++) { final Node oldChildNode = children.item(i); final Node newChildNode = convertFromNamespaceForm(oldChildNode); newElement.appendChild(newChildNode); }//from ww w . java 2 s. c om final NamedNodeMap attributes = node.getAttributes(); for (int i = 0, n = attributes.getLength(); i < n; i++) { final Attr attr = (Attr) attributes.item(i); final String attrQualifiedName = attr.getNodeName(); final String attrLocalName = attr.getLocalName(); if (!attrQualifiedName.equals(XMLNS) && !attrQualifiedName.startsWith(XMLNS_COLON) && !attrLocalName.equals(XSI_SCHEMA_LOCATION_ATTR)) { newElement.setAttributeNS(null, attrLocalName, attr.getValue()); } } return newElement; } else { return node.cloneNode(true); } }
From source file:com.laex.j2objc.AntDelegate.java
/** * Append exclude pattern to xml./*from w ww.j a v a 2s . co m*/ * * @param path * the path * @param pats * the pats * @throws ParserConfigurationException * the parser configuration exception * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. * @throws XPathExpressionException * the x path expression exception * @throws CoreException * the core exception * @throws TransformerException * the transformer exception */ private void appendExcludePatternToXML(IFile path, String[] pats) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, CoreException, TransformerException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse(path.getContents()); XPathFactory xpathfactory = XPathFactory.newInstance(); XPath xpath = xpathfactory.newXPath(); XPathExpression expr = xpath.compile("project/target/move/fileset"); Node node = (Node) expr.evaluate(dom, XPathConstants.NODE); NodeList children = node.getChildNodes(); // don't why the last node in the xml should be indexed by length - 2 Node excludeCopy = children.item(children.getLength() - 2).cloneNode(true); for (String pattern : pats) { if (StringUtils.isNotEmpty(pattern.trim())) { Node newnode = excludeCopy.cloneNode(true); newnode.getAttributes().getNamedItem("name").setNodeValue(pattern); node.appendChild(newnode); } } // Setup transformers TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); transformer.transform(new DOMSource(dom), new StreamResult(sw)); String output = sw.getBuffer().toString(); // save the ouput ByteArrayInputStream bis = new ByteArrayInputStream(output.getBytes("utf-8")); path.setContents(bis, 0, null); }
From source file:fi.csc.kapaVirtaAS.MessageTransformer.java
public String transform(String message, MessageDirection direction) throws Exception { try {//from www. ja v a 2s.c om DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = dBuilder .parse(new InputSource(new ByteArrayInputStream(stripXmlDefinition(message).getBytes()))); doc.setXmlVersion("1.0"); doc.normalizeDocument(); Element root = doc.getDocumentElement(); if (direction == MessageDirection.XRoadToVirta) { // Save XRoad schema prefix for response message xroadSchemaPrefix = namedNodeMapToStream(root.getAttributes()) .filter(node -> node .getNodeValue().toLowerCase().contains(conf.getXroadSchema().toLowerCase())) .findFirst() .orElseThrow( () -> new DOMException(DOMException.NOT_FOUND_ERR, "Xroad schema prefix not found")) .getNodeName(); xroadIdSchemaPrefix = namedNodeMapToStream(root.getAttributes()) .filter(node -> node.getNodeValue().toLowerCase() .contains(conf.getXroadIdSchema().toLowerCase())) .findFirst().orElseThrow(() -> new DOMException(DOMException.NOT_FOUND_ERR, "XroadId schema prefix not found")) .getNodeName(); // Change tns schema getNodeByKeyword(namedNodeMapToStream(root.getAttributes()), conf.getAdapterServiceSchema()) .map(attribute -> setNodeValueToNode(attribute, conf.getVirtaServiceSchema())); //There should be two children under the root node: header and body for (int i = 0; i < root.getChildNodes().getLength(); ++i) { Node child = root.getChildNodes().item(i); // Save soap-headers for reply message and remove child elements under soap-headers if (child.getNodeName().toLowerCase().contains("header")) { this.xroadHeaderElement = child.cloneNode(true); root.replaceChild(child.cloneNode(false), child); } // Change SOAP-body else if (child.getNodeName().toLowerCase().contains("body")) { for (int j = 0; j < child.getChildNodes().getLength(); ++j) { if (child.getChildNodes().item(j).getNodeType() == Node.ELEMENT_NODE) { doc.renameNode(child.getChildNodes().item(j), conf.getVirtaServiceSchema(), child.getChildNodes().item(j).getNodeName() + "Request"); break; } } } } } if (direction == MessageDirection.VirtaToXRoad) { // Add XRoad schemas with saved prefix to response message root.setAttribute(xroadSchemaPrefix, conf.getXroadSchema()); root.setAttribute(xroadIdSchemaPrefix, conf.getXroadIdSchema()); // Change tns schema getNodeByKeyword(namedNodeMapToStream(root.getAttributes()), conf.getVirtaServiceSchema()) .map(attribute -> setNodeValueToNode(attribute, conf.getAdapterServiceSchema())); // Change SOAP-headers Node headerNode = getNodeByKeyword(nodeListToStream(root.getChildNodes()), "header").get(); for (int i = 0; i < this.xroadHeaderElement.getChildNodes().getLength(); ++i) { headerNode.appendChild(doc.importNode(this.xroadHeaderElement.getChildNodes().item(i), true)); } // Change SOAP-body getNodeByKeyword(nodeListToStream(root.getChildNodes()), "body") .map(bodyNode -> removeAttribureFromElement(nodeToElement(bodyNode), virtaServicePrefix)) .map(bodyNode -> setAttributeToElement(nodeToElement(bodyNode), virtaServicePrefix, conf.getAdapterServiceSchema())); //Virta gives malformed soap fault message. Need to parse it correct. getNodeByKeyword(nodeListToStream(root.getChildNodes()), "body") .map(bodyNode -> nodeListToStream(bodyNode.getChildNodes())).map( nodesInBodyStream -> getNodeByKeyword(nodesInBodyStream, "fault") .map(faultNode -> removeAttribureFromElement( nodeToElement(nodeToElement(faultNode) .getElementsByTagName("faultstring").item(0)), "xml:lang"))); } doc.normalizeDocument(); DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(domSource, result); message = writer.toString(); return stripXmlDefinition(message); } catch (Exception e) { if (direction == MessageDirection.XRoadToVirta) { log.error("Error in parsing request message."); throw e; } else { log.error("Error in parsing response message"); log.error(e.toString()); return stripXmlDefinition(faultMessageService.generateSOAPFault(message, faultMessageService.getResValidFail(), this.xroadHeaderElement)); } } }
From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java
private Document parseXML(Resource resource, List<Rule> rules) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { debug("Now loading " + resource); try (InputStream in = resource.getInputStream()) { final Document doc = XMLRewrite.parseXML(in); rewriteXML(doc, rules, false, false); final List<Node> importNodes = evaluateXPath("/beans//import", doc); debug("Found " + importNodes.size() + " import statements"); for (Node importNode : importNodes) { debug("(1) Node has parent: " + importNode.getParentNode()); String path = importNode.getAttributes().getNamedItem("resource").getNodeValue(); if (path.startsWith("classpath:")) { path = path.substring("classpath:".length()); }//from w ww. ja va 2 s . co m debug("Including '" + path + "' , now at " + resource); final Resource imported; if (path.startsWith("/")) { // absolute imported = new ClassPathResource(path); } else { imported = resource.createRelative(path); } final Document importedXML = parseXML(imported, rules); mergeAttributes(importedXML.getFirstChild(), doc.getFirstChild(), doc); final List<Node> beans = wrapNodeList(importedXML.getFirstChild().getChildNodes()); for (Node beanNode : beans) { final Node adoptedNode = doc.adoptNode(beanNode.cloneNode(true)); importNode.getParentNode().insertBefore(adoptedNode, importNode); } importNode.getParentNode().removeChild(importNode); } debug("*** return ***"); return doc; } catch (Exception e) { throw new RuntimeException("Failed to load XML from '" + resource + "'", e); } }
From source file:de.betterform.xml.xforms.ui.Repeat.java
private void initializePrototype(Node parent, Node prototype) { Node copy = prototype.cloneNode(false); if (copy.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) copy; if (element.getAttributeNS(null, "id").length() == 0 && XFormsElementFactory.isUIElement(element)) { element.setAttributeNS(null, "id", this.container.generateId()); }//from w ww . j ava 2 s . c o m NodeList children = prototype.getChildNodes(); for (int index = 0; index < children.getLength(); index++) { initializePrototype(element, children.item(index)); } } parent.appendChild(copy); }