Example usage for org.w3c.dom Node appendChild

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

Introduction

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

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Implementation for <code>org.w3c.dom.Node</code> :
 * converts the Node to a SAX event stream.
 *
 * @param parent The node getting the value
 * @param v the value//from  ww w .ja  va 2 s. c o  m
 */
public static void valueOf(Node parent, Node v) throws ProcessingException {
    if (v != null) {
        parent.appendChild(parent.getOwnerDocument().importNode(v, true));
    }
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Implementation for <code>java.util.Map</code> :
 * For each entry an element is created with the childs key and value
 * Outputs the value and the key by calling {@link #valueOf(Node, Object)}
 * on each value and key of the Map.//from   ww w . j a v a2s  . c om
 *
 * @param parent The node getting the value
 * @param v      the Map
 */
public static void valueOf(Node parent, Map v) throws ProcessingException {
    if (v != null) {
        Node mapNode = parent.getOwnerDocument().createElementNS(null, "java.util.map");
        parent.appendChild(mapNode);
        for (Iterator iter = v.entrySet().iterator(); iter.hasNext();) {
            Map.Entry me = (Map.Entry) iter.next();

            Node entryNode = mapNode.getOwnerDocument().createElementNS(null, "entry");
            mapNode.appendChild(entryNode);

            Node keyNode = entryNode.getOwnerDocument().createElementNS(null, "key");
            entryNode.appendChild(keyNode);
            valueOf(keyNode, me.getKey());

            Node valueNode = entryNode.getOwnerDocument().createElementNS(null, "value");
            entryNode.appendChild(valueNode);
            valueOf(valueNode, me.getValue());
        }
    }
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Return the <CODE>Node</CODE> from the DOM Node <CODE>rootNode</CODE>
 * using the XPath expression <CODE>path</CODE>.
 * If the node does not exist, it is created and then returned.
 * This is a very simple method for creating new nodes. If the
 * XPath contains selectors ([,,,]) or "*" it is of course not
 * possible to create the new node. So if you use such XPaths
 * the node must exist beforehand.// w  w w.j a  va  2 s .c o m
 * An simple exception is if the expression contains attribute
 * test to values (e.g. [@id = 'du' and @number = 'you'],
 * the attributes with the given values are added. The attributes
 * must be separated with 'and'.
 * Another problem are namespaces: XPath requires sometimes selectors for
 * namespaces, e.g. : /*[namespace-uri()="uri" and local-name()="name"]
 * Creating such a node with a namespace is not possible right now as we use
 * a very simple XPath parser which is not able to parse all kinds of selectors
 * correctly.
 *
 * @param rootNode The node to start the search.
 * @param path     XPath expression for searching the node.
 * @return         The node specified by the path.
 * @throws ProcessingException If no path is specified or the XPath engine fails.
 * @deprecated
 */
public static Node selectSingleNode(Node rootNode, String path) throws ProcessingException {
    // Now we have to parse the string
    // First test:  path? rootNode?
    if (path == null) {
        throw new ProcessingException("XPath is required.");
    }
    if (rootNode == null)
        return rootNode;

    if (path.length() == 0 || path.equals("/") == true)
        return rootNode;

    // now the first "quick" test is if the node exists using the
    // full XPathAPI
    try {
        Node testNode = getSingleNode(rootNode, path);
        if (testNode != null)
            return testNode;
    } catch (javax.xml.transform.TransformerException local) {
        throw new ProcessingException(
                "Transforming exception during selectSingleNode with path: '" + path + "'. Exception: " + local,
                local);
    }
    // Remove leading "/" on both ends
    path = StringUtils.strip(path, "/");

    // now step through the nodes!
    Node parent = rootNode;
    int pos;
    int posSelector;
    do {
        pos = path.indexOf("/"); // get next separator
        posSelector = path.indexOf("[");
        if (posSelector != -1 && posSelector < pos) {
            posSelector = path.indexOf("]");
            pos = path.indexOf("/", posSelector);
        }

        String nodeName;
        boolean isAttribute = false;
        if (pos != -1) { // found separator
            nodeName = path.substring(0, pos); // string until "/"
            path = path.substring(pos + 1); // rest of string after "/"
        } else {
            nodeName = path;
        }

        // test for attribute spec
        if (nodeName.startsWith("@") == true) {
            isAttribute = true;
        }

        Node singleNode;
        try {
            singleNode = getSingleNode(parent, nodeName);
        } catch (javax.xml.transform.TransformerException localException) {
            throw new ProcessingException("XPathUtil.selectSingleNode: " + localException.getMessage(),
                    localException);
        }

        // create node if necessary
        if (singleNode == null) {
            Node newNode;
            // delete XPath selectors
            int posSelect = nodeName.indexOf("[");
            String XPathExp = null;
            if (posSelect != -1) {
                XPathExp = nodeName.substring(posSelect + 1, nodeName.length() - 1);
                nodeName = nodeName.substring(0, posSelect);
            }
            if (isAttribute == true) {
                try {
                    newNode = getOwnerDocument(rootNode).createAttributeNS(null, nodeName.substring(1));
                    ((Element) parent).setAttributeNodeNS((org.w3c.dom.Attr) newNode);
                    parent = newNode;
                } catch (DOMException local) {
                    throw new ProcessingException("Unable to create new DOM node: '" + nodeName + "'.", local);
                }
            } else {
                try {
                    newNode = getOwnerDocument(rootNode).createElementNS(null, nodeName);
                } catch (DOMException local) {
                    throw new ProcessingException("Unable to create new DOM node: '" + nodeName + "'.", local);
                }
                if (XPathExp != null) {
                    java.util.List attrValuePairs = new java.util.ArrayList(4);
                    boolean noError = true;

                    String attr;
                    String value;
                    // scan for attributes
                    java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(XPathExp, "= ");
                    while (tokenizer.hasMoreTokens() == true) {
                        attr = tokenizer.nextToken();
                        if (attr.startsWith("@") == true) {
                            if (tokenizer.hasMoreTokens() == true) {
                                value = tokenizer.nextToken();
                                if (value.startsWith("'") && value.endsWith("'"))
                                    value = value.substring(1, value.length() - 1);
                                if (value.startsWith("\"") && value.endsWith("\""))
                                    value = value.substring(1, value.length() - 1);
                                attrValuePairs.add(attr.substring(1));
                                attrValuePairs.add(value);
                            } else {
                                noError = false;
                            }
                        } else if (attr.trim().equals("and") == false) {
                            noError = false;
                        }
                    }
                    if (noError == true) {
                        for (int l = 0; l < attrValuePairs.size(); l = l + 2) {
                            ((Element) newNode).setAttributeNS(null, (String) attrValuePairs.get(l),
                                    (String) attrValuePairs.get(l + 1));
                        }
                    }
                }
                parent.appendChild(newNode);
                parent = newNode;
            }
        } else {
            parent = singleNode;
        }
    } while (pos != -1);
    return parent;
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Return the <CODE>Node</CODE> from the DOM Node <CODE>rootNode</CODE>
 * using the XPath expression <CODE>path</CODE>.
 * If the node does not exist, it is created and then returned.
 * This is a very simple method for creating new nodes. If the
 * XPath contains selectors ([,,,]) or "*" it is of course not
 * possible to create the new node. So if you use such XPaths
 * the node must exist beforehand./*from   www  .  ja  v a2  s  .  c  o  m*/
 * An simple exception is if the expression contains attribute
 * test to values (e.g. [@id = 'du' and @number = 'you'],
 * the attributes with the given values are added. The attributes
 * must be separated with 'and'.
 * Another problem are namespaces: XPath requires sometimes selectors for
 * namespaces, e.g. : /*[namespace-uri()="uri" and local-name()="name"]
 * Creating such a node with a namespace is not possible right now as we use
 * a very simple XPath parser which is not able to parse all kinds of selectors
 * correctly.
 *
 * @param rootNode  The node to start the search.
 * @param path      XPath expression for searching the node.
 * @param processor The XPath processor to use
 * @return          The node specified by the path.
 * @throws ProcessingException If no path is specified or the XPath engine fails.
 */
public static Node selectSingleNode(Node rootNode, String path, XPathProcessor processor)
        throws ProcessingException {
    // Now we have to parse the string
    // First test:  path? rootNode?
    if (path == null) {
        throw new ProcessingException("XPath is required.");
    }
    if (rootNode == null)
        return rootNode;

    if (path.length() == 0 || path.equals("/") == true)
        return rootNode;

    // now the first "quick" test is if the node exists using the
    // full XPathAPI
    try {
        Node testNode = getSingleNode(rootNode, path, processor);
        if (testNode != null)
            return testNode;
    } catch (javax.xml.transform.TransformerException local) {
        throw new ProcessingException(
                "Transforming exception during selectSingleNode with path: '" + path + "'. Exception: " + local,
                local);
    }

    // remove leading "/" oon both ends
    path = StringUtils.strip(path, "/");

    // now step through the nodes!
    Node parent = rootNode;
    int pos;
    int posSelector;
    do {
        pos = path.indexOf("/"); // get next separator
        posSelector = path.indexOf("[");
        if (posSelector != -1 && posSelector < pos) {
            posSelector = path.indexOf("]");
            pos = path.indexOf("/", posSelector);
        }

        String nodeName;
        boolean isAttribute = false;
        if (pos != -1) { // found separator
            nodeName = path.substring(0, pos); // string until "/"
            path = path.substring(pos + 1); // rest of string after "/"
        } else {
            nodeName = path;
        }

        // test for attribute spec
        if (nodeName.startsWith("@") == true) {
            isAttribute = true;
        }

        Node singleNode;
        try {
            singleNode = getSingleNode(parent, nodeName, processor);
        } catch (javax.xml.transform.TransformerException localException) {
            throw new ProcessingException("XPathUtil.selectSingleNode: " + localException.getMessage(),
                    localException);
        }

        // create node if necessary
        if (singleNode == null) {
            Node newNode;
            // delete XPath selectors
            int posSelect = nodeName.indexOf("[");
            String XPathExp = null;
            if (posSelect != -1) {
                XPathExp = nodeName.substring(posSelect + 1, nodeName.length() - 1);
                nodeName = nodeName.substring(0, posSelect);
            }
            if (isAttribute == true) {
                try {
                    newNode = getOwnerDocument(rootNode).createAttributeNS(null, nodeName.substring(1));
                    ((Element) parent).setAttributeNodeNS((org.w3c.dom.Attr) newNode);
                    parent = newNode;
                } catch (DOMException local) {
                    throw new ProcessingException("Unable to create new DOM node: '" + nodeName + "'.", local);
                }
            } else {
                try {
                    newNode = getOwnerDocument(rootNode).createElementNS(null, nodeName);
                } catch (DOMException local) {
                    throw new ProcessingException("Unable to create new DOM node: '" + nodeName + "'.", local);
                }
                if (XPathExp != null) {
                    java.util.List attrValuePairs = new java.util.ArrayList(4);
                    boolean noError = true;

                    String attr;
                    String value;
                    // scan for attributes
                    java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(XPathExp, "= ");
                    while (tokenizer.hasMoreTokens() == true) {
                        attr = tokenizer.nextToken();
                        if (attr.startsWith("@") == true) {
                            if (tokenizer.hasMoreTokens() == true) {
                                value = tokenizer.nextToken();
                                if (value.startsWith("'") && value.endsWith("'"))
                                    value = value.substring(1, value.length() - 1);
                                if (value.startsWith("\"") && value.endsWith("\""))
                                    value = value.substring(1, value.length() - 1);
                                attrValuePairs.add(attr.substring(1));
                                attrValuePairs.add(value);
                            } else {
                                noError = false;
                            }
                        } else if (attr.trim().equals("and") == false) {
                            noError = false;
                        }
                    }
                    if (noError == true) {
                        for (int l = 0; l < attrValuePairs.size(); l = l + 2) {
                            ((Element) newNode).setAttributeNS(null, (String) attrValuePairs.get(l),
                                    (String) attrValuePairs.get(l + 1));
                        }
                    }
                }
                parent.appendChild(newNode);
                parent = newNode;
            }
        } else {
            parent = singleNode;
        }
    } while (pos != -1);
    return parent;
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Use a path to select the first occurence of a node. The namespace
 * of a node is ignored!//  w w w.  j  a  v  a 2s. com
 * @param contextNode The node starting the search.
 * @param path        The path to search the node. The
 *                    contextNode is searched for a child named path[0],
 *                    this node is searched for a child named path[1]...
 * @param create      If a child with the corresponding name is not found
 *                    and create is set, this node will be created.
*/
public static Node getFirstNodeFromPath(Node contextNode, final String[] path, final boolean create) {
    if (contextNode == null || path == null || path.length == 0)
        return contextNode;
    // first test if the node exists
    Node item = getFirstNodeFromPath(contextNode, path, 0);
    if (item == null && create == true) {
        int i = 0;
        NodeList childs;
        boolean found;
        int m, l;
        while (contextNode != null && i < path.length) {
            childs = contextNode.getChildNodes();
            found = false;
            if (childs != null) {
                m = 0;
                l = childs.getLength();
                while (found == false && m < l) {
                    item = childs.item(m);
                    if (item.getNodeType() == Node.ELEMENT_NODE
                            && item.getLocalName().equals(path[i]) == true) {
                        found = true;
                        contextNode = item;
                    }
                    m++;
                }
            }
            if (found == false) {
                Element e = contextNode.getOwnerDocument().createElementNS(null, path[i]);
                contextNode.appendChild(e);
                contextNode = e;
            }
            i++;
        }
        item = contextNode;
    }
    return item;
}

From source file:org.apache.geode.management.internal.configuration.utils.XmlUtils.java

/*****
 * Adds a new node or replaces an existing node in the Document
 * //w ww  . j a v  a  2 s  .  co  m
 * @param doc Target document where the node will added
 * @param xmlEntity contains definition of the xml entity
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws XPathExpressionException
 */
public static void addNewNode(final Document doc, final XmlEntity xmlEntity)
        throws IOException, XPathExpressionException, SAXException, ParserConfigurationException {
    // Build up map per call to avoid issues with caching wrong version of the map.
    final LinkedHashMap<String, CacheElement> elementOrderMap = CacheElement.buildElementMap(doc);

    final Node newNode = createNode(doc, xmlEntity.getXmlDefinition());
    final Node root = doc.getDocumentElement();
    final int incomingElementOrder = getElementOrder(elementOrderMap, xmlEntity.getNamespace(),
            xmlEntity.getType());

    boolean nodeAdded = false;
    NodeList nodes = root.getChildNodes();
    final int length = nodes.getLength();
    for (int i = 0; i < length; i++) {
        final Node node = nodes.item(i);

        if (node instanceof Element) {
            final Element childElement = (Element) node;
            final String type = childElement.getLocalName();
            final String namespace = childElement.getNamespaceURI();

            if (namespace.equals(xmlEntity.getNamespace()) && type.equals(xmlEntity.getType())) {
                // First check if the element has a name
                String nameOrId = getAttribute(childElement, "name");
                // If not then check if the element has an Id
                if (nameOrId == null) {
                    nameOrId = getAttribute(childElement, "id");
                }

                if (nameOrId != null) {
                    // If there is a match , then replace the existing node with the incoming node
                    if (nameOrId.equals(xmlEntity.getNameOrId())) {
                        root.replaceChild(newNode, node);
                        nodeAdded = true;
                        break;
                    }
                } else {
                    // This element does not have any name or id identifier for e.g PDX and gateway-receiver
                    // If there is only one element of that type then replace it with the incoming node
                    if (!isMultiple(elementOrderMap, namespace, type)) {
                        root.replaceChild(newNode, node);
                        nodeAdded = true;
                        break;
                    }
                }
            } else {
                if (incomingElementOrder < getElementOrder(elementOrderMap, namespace, type)) {
                    root.insertBefore(newNode, node);
                    nodeAdded = true;
                    break;
                }
            }
        }
    }
    if (!nodeAdded) {
        root.appendChild(newNode);
    }
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlFilterReader.java

private void processCharacters(Characters event) throws XPathExpressionException {
    //System.out.println( "T[" + event.isCData() + "," + event.isWhiteSpace() + "," + event.isIgnorableWhiteSpace() + "]=" + event );
    Level level = stack.peek();/*ww  w .j  a  va  2s.  c o m*/
    Node node = stack.peek().node;
    if (event.isCData()) {
        node.appendChild(document.createCDATASection(event.getData()));
    } else {
        node.appendChild(document.createTextNode(event.getData()));
    }
    if (!currentlyBuffering()) {
        String value = event.getData();
        if (!event.isWhiteSpace()) {
            if (level.scopeConfig == null || level.scopeConfig.getSelectors().isEmpty()) {
                value = filterText(extractQName(node), value, null);
            } else {
                UrlRewriteFilterPathDescriptor path = pickFirstMatchingPath(level);
                if (path instanceof UrlRewriteFilterApplyDescriptor) {
                    String rule = ((UrlRewriteFilterApplyDescriptor) path).rule();
                    value = filterText(extractQName(node), value, rule);
                }
            }
        }
        if (event.isCData()) {
            writer.write("<![CDATA[");
            writer.write(value);
            writer.write("]]>");
        } else {
            writer.write(StringEscapeUtils.escapeXml(value));
        }
    }
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMReference.java

public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) throws MarshalException {
    if (log.isDebugEnabled()) {
        log.debug("Marshalling Reference");
    }//from w  ww . ja va2 s  .  co m
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    refElem = DOMUtils.createElement(ownerDoc, "Reference", XMLSignature.XMLNS, dsPrefix);

    // set attributes
    DOMUtils.setAttributeID(refElem, "Id", id);
    DOMUtils.setAttribute(refElem, "URI", uri);
    DOMUtils.setAttribute(refElem, "Type", type);

    // create and append Transforms element
    if (!allTransforms.isEmpty()) {
        Element transformsElem = DOMUtils.createElement(ownerDoc, "Transforms", XMLSignature.XMLNS, dsPrefix);
        refElem.appendChild(transformsElem);
        for (Transform transform : allTransforms) {
            ((DOMStructure) transform).marshal(transformsElem, dsPrefix, context);
        }
    }

    // create and append DigestMethod element
    ((DOMDigestMethod) digestMethod).marshal(refElem, dsPrefix, context);

    // create and append DigestValue element
    if (log.isDebugEnabled()) {
        log.debug("Adding digestValueElem");
    }
    Element digestValueElem = DOMUtils.createElement(ownerDoc, "DigestValue", XMLSignature.XMLNS, dsPrefix);
    if (digestValue != null) {
        digestValueElem.appendChild(ownerDoc.createTextNode(Base64.encode(digestValue)));
    }
    refElem.appendChild(digestValueElem);

    parent.appendChild(refElem);
    here = refElem.getAttributeNodeNS(null, "URI");
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo.java

public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) throws MarshalException {
    ownerDoc = DOMUtils.getOwnerDocument(parent);
    Element siElem = DOMUtils.createElement(ownerDoc, "SignedInfo", XMLSignature.XMLNS, dsPrefix);

    // create and append CanonicalizationMethod element
    DOMCanonicalizationMethod dcm = (DOMCanonicalizationMethod) canonicalizationMethod;
    dcm.marshal(siElem, dsPrefix, context);

    // create and append SignatureMethod element
    ((DOMStructure) signatureMethod).marshal(siElem, dsPrefix, context);

    // create and append Reference elements
    for (Reference reference : references) {
        ((DOMReference) reference).marshal(siElem, dsPrefix, context);
    }//ww  w .  ja  va 2  s  .com

    // append Id attribute
    DOMUtils.setAttributeID(siElem, "Id", id);

    parent.appendChild(siElem);
    localSiElem = siElem;
}

From source file:org.apache.nutch.searcher.response.xml.XMLResponseWriter.java

/**
 * Creates and returns a new node within the XML document.
 * /*from  ww  w.  j  a  va2s  . co  m*/
 * @param doc The XML document.
 * @param parent The parent Node.
 * @param name The name of the new node.
 * 
 * @return The newly created node Element.
 */
private static Element addNode(Document doc, Node parent, String name) {
    Element child = doc.createElement(name);
    parent.appendChild(child);
    return child;
}