Example usage for org.w3c.dom Node getOwnerDocument

List of usage examples for org.w3c.dom Node getOwnerDocument

Introduction

In this page you can find the example usage for org.w3c.dom Node getOwnerDocument.

Prototype

public Document getOwnerDocument();

Source Link

Document

The Document object associated with this node.

Usage

From source file:Main.java

/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.//from w ww . j  a v a2s  .  c om
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start = src;
    Node parent = src;
    Node place = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr) attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl) element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException(
                    "can't copy node type, " + type + " (" + node.getNodeName() + ')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place = place.getFirstChild();
            dest = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place = parent.getNextSibling();
                parent = parent.getParentNode();
                dest = dest.getParentNode();
            }
        }

    }

}

From source file:Main.java

/**
 * Adds a new {@link Element} with multiple attributes to the given parent
 * {@link Element}. The attribute data should be passed in via a {@link Map},
 * with each entry containing an attribute name as key and attribute value as the value.
 * /* www .jav a 2  s. com*/
 * @param doc
 * @param parent
 * @param name
 * @param attributeData
 * @return
 */
public static Element addElement(Document doc, Node parent, String name, Map<String, String> attributeData) {
    if (doc == null) {
        doc = parent.getOwnerDocument();
    }
    final Element elem = addElement(doc, parent, name);
    if (null != attributeData && !attributeData.isEmpty()) {
        Iterator<Map.Entry<String, String>> iter = attributeData.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = iter.next();
            elem.setAttribute(entry.getKey(), entry.getValue());
        }
    }
    return elem;
}

From source file:Main.java

public static Node addChildNode(Node pNode, String name, String value) {
    Document _doc = null;/*from www . j a va 2 s  .com*/
    if (pNode.getNodeType() == Node.DOCUMENT_NODE) {
        _doc = (Document) pNode;
    } else {
        _doc = pNode.getOwnerDocument();
    }

    Element _ele = _doc.createElement(name);
    Node _node = _doc.createTextNode(value);
    _ele.appendChild(_node);

    return pNode.appendChild(_ele);
}

From source file:Main.java

public static ArrayList<Node> getNodeList(Node parentNode, String nodeName, Map<String, String> attributesMap) {
    ArrayList<Node> returnNodeList = new ArrayList<Node>();
    try {/* w  ww.ja va 2  s .c o m*/
        DocumentTraversal dt = (DocumentTraversal) parentNode.getOwnerDocument();
        NodeIterator i = dt.createNodeIterator(parentNode, NodeFilter.SHOW_ELEMENT, null, false);
        Node node = i.nextNode();
        while (node != null) {
            if (node.getNodeName().equals(nodeName)) {
                if (attributesExist(node, attributesMap)) {
                    returnNodeList.add(node);
                }
            }
            node = i.nextNode();
        }
    } catch (Exception ex) {
        logger.error(ex);
    }
    return returnNodeList;
}

From source file:Main.java

public static Element createNewElement(Node elem, String tag) {// throws Exception {
    if (elem instanceof Document) {
        Document doc = (Document) elem;
        Element res = doc.createElement(tag);
        elem.appendChild(res);/* w  w w  .  j  a  va  2s. c o  m*/
        return res;
    } else {
        Document doc = elem.getOwnerDocument();
        Element res = doc.createElement(tag);
        elem.appendChild(res);
        return res;
    }
}

From source file:Main.java

public static Node appendXMLChildFromString(Node parent, String child)
        throws ParserConfigurationException, SAXException, IOException {
    if (parent instanceof Document)
        parent = ((Document) parent).getDocumentElement();
    Document newDoc = getXMLFromString(child);
    Node newNode = parent.getOwnerDocument().importNode(newDoc.getDocumentElement(), true);
    return parent.appendChild(newNode);
}

From source file:Main.java

public static Node prependXMLChildFromString(Node parent, String child)
        throws ParserConfigurationException, SAXException, IOException {
    if (parent instanceof Document)
        parent = ((Document) parent).getDocumentElement();
    Document newDoc = getXMLFromString(child);
    Node newNode = parent.getOwnerDocument().importNode(newDoc.getDocumentElement(), true);
    return parent.insertBefore(newNode, parent.getFirstChild());
}

From source file:Main.java

/**
 * @param n// www. ja v  a  2 s.  c om
 *            the node
 * @return the first element in the ancestor tree of {@code n}. If
 *         {@code n} is an {@link Element}, {@code n} is returned. If
 *         {@code n} is <code>null</code>, this method returns
 *         <code>null</code>.
 */
public static Element getAncestorElement(Node n) {
    if (n == null) {
        return null;
    }
    if (n.getNodeType() == Node.ELEMENT_NODE) {
        return (Element) n;
    }
    Node parent = n.getParentNode();
    if (parent == null) {
        Document doc = (Document) (n instanceof Document ? n : n.getOwnerDocument());
        return doc == null ? null : doc.getDocumentElement();
    }
    return getAncestorElement(parent);
}

From source file:Main.java

public static Node createAndAppendNode(Node root, String path) {
    if (path == null)
        return root;

    Element node = null;/*  w ww .  ja  v a2s  .  c o  m*/
    if (path.contains("/")) // check if path is complex
    {
        String[] steps = path.split("/");
        Node upper = root;
        Node lower = null;
        for (int i = 0; i < steps.length; i++) {
            // check if element exists
            lower = ifNodeExists(upper, steps[i]);
            if (lower == null) {
                lower = upper.getOwnerDocument().createElement(steps[i]);
                upper.appendChild(lower);
            }
            upper = lower;
        }
        return lower;
    }
    // simple path:
    node = root.getOwnerDocument().createElement(path);
    root.appendChild(node);
    return node;
}

From source file:Main.java

/**
 * recursively transform the prefix and the namespace of a node where getNamespaceURI is NULL
 * @param node the node to transform/*from   ww  w. j av a2 s.  c  o m*/
 * @param prefix the new prefix
 * @param namespaceuri the new namespace uri
 * @return the new node with NS and prefix changed
 */
static public Node setPrefixNamespace(Node node, String prefix, String namespaceuri) {
    Node dest = null;
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element e = (Element) node;
        if (e.getNamespaceURI() == null) {

            Element e2 = node.getOwnerDocument().createElementNS(namespaceuri,
                    (prefix != null ? prefix + ':' + e.getLocalName() : e.getLocalName()));
            NamedNodeMap nodes = e.getAttributes();
            for (int i = 0; i < nodes.getLength(); ++i) {
                Attr att = (Attr) (node.getOwnerDocument().importNode(nodes.item(i), true));
                e2.setAttributeNode(att);
            }
            dest = e2;
        } else {
            dest = node.getOwnerDocument().importNode(node, false);
        }
    } else {
        dest = node.getOwnerDocument().importNode(node, false);
    }

    for (Node c = node.getFirstChild(); c != null; c = c.getNextSibling()) {
        dest.appendChild(setPrefixNamespace(c, prefix, namespaceuri));
    }
    return dest;
}