Example usage for org.w3c.dom Document importNode

List of usage examples for org.w3c.dom Document importNode

Introduction

In this page you can find the example usage for org.w3c.dom Document importNode.

Prototype

public Node importNode(Node importedNode, boolean deep) throws DOMException;

Source Link

Document

Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node.

Usage

From source file:Main.java

public static void setByPath(Document doc, String path, Node in) {
    Node node = getNodeByPath(doc, path);
    if (in.getNodeType() == Node.DOCUMENT_NODE) {
        in = in.getFirstChild();//from   w  ww.j  a  v  a 2  s  .  co  m
    }
    Node newNode = doc.importNode(in, true);
    node.getParentNode().replaceChild(newNode, node);
}

From source file:Main.java

public static Element cloneElementAs(Element srcEl, Document dstDoc, String elName) {
    if (srcEl.getNodeName().equals(elName)) {
        if (srcEl.getOwnerDocument() == dstDoc) {
            return (Element) srcEl.cloneNode(true);
        } else {/*from  w w w .  j av  a2  s  .c o m*/
            return (Element) dstDoc.importNode(srcEl, true);
        }
    } else {
        final Element dstEl = dstDoc.createElement(elName);
        final NodeList srcChildren = srcEl.getChildNodes();
        final int n = srcChildren.getLength();
        for (int i = 0; i < n; ++i) {
            final Node srcChild = srcChildren.item(i);
            final Node dstChild = dstDoc.importNode(srcChild, true);
            dstEl.appendChild(dstChild);
        }
        return dstEl;
    }
}

From source file:Main.java

public static void moveElement(Document fromDoc, Document toDoc, Element root, String elementName) {
    NodeList list = fromDoc.getElementsByTagName(elementName);
    if ((list != null) && (list.getLength() > 0)) {
        Element element = (Element) list.item(0);
        Node node = toDoc.importNode(element, true);
        root.appendChild(node);//from   ww  w.  j  a v a  2 s .  c o m
        element.getParentNode().removeChild(element);
    }
}

From source file:DOMEdit.java

public static void importName(Document doc1, Document doc2) {
        Element root1 = doc1.getDocumentElement();
        Element personInDoc1 = (Element) root1.getFirstChild();

        Node importedPerson = doc2.importNode(personInDoc1, true);

        Element root2 = doc2.getDocumentElement();
        root2.appendChild(importedPerson);
    }/*  w ww .j  a va  2 s  .c o  m*/

From source file:com.twentyn.patentExtractor.Util.java

public static Document nodeToDocument(DocumentBuilder docBuilder, String documentContainer, Node n) {
    /* With help from://from  www.j av  a2  s .  c o  m
     * http://examples.javacodegeeks.com/core-java/xml/dom/copy-nodes-subtree-from-one-dom-document-to-another/ */
    org.w3c.dom.Document newDoc = docBuilder.newDocument();
    Element rootElement = newDoc.createElement(documentContainer);
    Node newNode = newDoc.importNode(n, true);
    rootElement.appendChild(newNode);
    newDoc.appendChild(rootElement);
    return newDoc;
}

From source file:Main.java

/**
 * Changes the tag name of an element./*w  w  w .ja  va2  s. co m*/
 * 
 * @param elem Element which name should be changed
 * @param newName new tag name of the element
 * @return true if the name was changed successfully or false otherwise
 */
static public boolean changeTagName(Element elem, String newName) {
    if (elem == null)
        return false; // not Found!
    Document doc = elem.getOwnerDocument();
    Element newElem = doc.createElement(newName);

    // Copy the attributes to the new element
    NamedNodeMap attrs = elem.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr2 = (Attr) doc.importNode(attrs.item(i), true);
        newElem.getAttributes().setNamedItem(attr2);
    }

    // Copy all Child Elements
    for (Node node = elem.getFirstChild(); node != null; node = node.getNextSibling())
        newElem.appendChild(node.cloneNode(true));
    // insert
    Node parent = elem.getParentNode();
    parent.replaceChild(newElem, elem);
    return true;
}

From source file:Main.java

/**
 * Create a new document object with input element as the root.
 * //from   ww  w  . ja v  a 2s.  c  o m
 * @param inputElement
 *            Input Element object
 * @param deep
 *            Include child nodes of this element true/false
 * @return XML Document object
 * @throws IllegalArgumentException
 *             if input is invalid
 * @throws ParserConfigurationException
 */
public static Document getDocument(final Element inputElement, final boolean deep)
        throws IllegalArgumentException, ParserConfigurationException {
    // Validate input element
    if (inputElement == null) {
        throw new IllegalArgumentException("Input element cannot be null in " + "XmlUtils.getDocument method");
    }

    // Create a new document
    final Document outputDocument = getDocument();

    // Import data from input element and
    // set as root element for output document
    outputDocument.appendChild(outputDocument.importNode(inputElement, deep));

    // return output document
    return outputDocument;
}

From source file:com.twentyn.patentExtractor.PatentDocumentFeatures.java

/**
 * Extracts sentence nodes from a POS-tagger XML document.  These sentences are intended to provide some notion of
 * locality for identified chemical entities.
 *
 * @param docBuilder A document builder to use when producing single-sentence XML documents.
 * @param doc        The POS-tagger XML document from which to extract sentences.
 * @return A list of single-sentence documents.
 * @throws ParserConfigurationException// w ww.  ja v  a 2 s . co  m
 * @throws XPathExpressionException
 */
private static List<Document> findSentences(DocumentBuilder docBuilder, Document doc)
        throws ParserConfigurationException, XPathExpressionException {
    if (doc != null) {
        // TODO: is there a more efficient yet still safe way to do this?
        XPath xpath = Util.getXPathFactory().newXPath();
        // TODO: get rid of this inline xpath compilation, run during setup.
        NodeList nodes = (NodeList) xpath.evaluate(SENTENCE_PATH, doc, XPathConstants.NODESET);

        List<Document> docList = new ArrayList<>(nodes.getLength());
        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);

            /* With help from:
             * http://examples.javacodegeeks.com/core-java/xml/dom/copy-nodes-subtree-from-one-dom-document-to-another/ */
            org.w3c.dom.Document newDoc = docBuilder.newDocument();
            Element rootElement = newDoc.createElement(SENTENCE_DOC_HEADER);
            Node newNode = newDoc.importNode(n, true);
            rootElement.appendChild(newNode);
            newDoc.appendChild(rootElement);
            docList.add(newDoc);
        }
        return docList;
    } else {
        // TODO: log here.
        return new ArrayList<>(0);
    }
}

From source file:com.sinet.gage.dlap.utils.XMLUtils.java

/**
 * @param String// w  w w.j av a 2s.co  m
 * @param String
 * @return String
 */
public static String parseXML(String xml, String rootElementName) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        DocumentBuilder db;
        db = dbf.newDocumentBuilder();
        Document newDoc = db.parse(new ByteArrayInputStream(xml.getBytes()));

        Element element = (Element) newDoc.getElementsByTagName(rootElementName).item(0);
        // Imports a node from another document to this document,
        // without altering
        Document newDoc2 = db.newDocument();
        // or removing the source node from the original document
        Node copiedNode = newDoc2.importNode(element, true);
        // Adds the node to the end of the list of children of this node
        newDoc2.appendChild(copiedNode);

        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tf.setOutputProperty(OutputKeys.INDENT, "yes");

        Writer out = new StringWriter();

        tf.transform(new DOMSource(newDoc2), new StreamResult(out));

        return out.toString();
    } catch (TransformerException | ParserConfigurationException | SAXException | IOException e) {
        LOGGER.error("Exception in parsing xml from response: ", e);
    }
    return "";
}

From source file:Main.java

/** Parse a valid xml string and return the Element representing this string. */
public static Element parseXMLString(Document document, String string)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);// www.ja v  a  2s  .co m
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document subDoc = builder.parse(new InputSource(new StringReader(string)));
    Element e = subDoc.getDocumentElement();
    return (Element) document.importNode(e, true);
}