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.dhatim.edisax.util.EdimapWriter.java

private Element newElement(String name, Node parent) {
    Element element = doc.createElementNS(NS, "medi:" + name);
    parent.appendChild(element);
    return element;
}

From source file:org.dhatim.templating.AbstractTemplateProcessor.java

private void _processTemplateAction(Element element, Node node, Action action,
        ExecutionContext executionContext) {
    Node parent = element.getParentNode();

    // Can't insert before or after the root element...
    if (parent instanceof Document && (action == Action.INSERT_BEFORE || action == Action.INSERT_AFTER)) {
        logger.debug("Insert before/after root element not allowed.  Consider using the replace action!!");
        return;/* ww w  . j ava  2  s .c  o  m*/
    }

    String outputStreamResourceName = getOutputStreamResource();
    if (outputStreamResourceName != null) {
        Writer writer = AbstractOutputStreamResource.getOutputWriter(outputStreamResourceName,
                executionContext);
        String text = extractTextContent(node, executionContext);
        try {
            writer.write(text);
        } catch (IOException e) {
            throw new SmooksException(
                    "Failed to write to output stream resource '" + outputStreamResourceName + "'.", e);
        }
    } else {
        if (action == Action.ADDTO) {
            element.appendChild(node);
        } else if (action == Action.INSERT_BEFORE) {
            DomUtils.insertBefore(node, element);
        } else if (action == Action.INSERT_AFTER) {
            Node nextSibling = element.getNextSibling();

            if (nextSibling == null) {
                // "element" is the last child of "parent" so just add to "parent".
                parent.appendChild(node);
            } else {
                // insert before the "nextSibling" - Node doesn't have an "insertAfter" operation!
                DomUtils.insertBefore(node, nextSibling);
            }
        } else if (action == Action.BIND_TO) {
            String text = extractTextContent(node, executionContext);

            executionContext.getBeanContext().addBean(bindBeanId, text, new Fragment(element));
        } else if (action == Action.REPLACE) {
            // Don't perform any "replace" actions here!
        }
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Copy child node references from source to target.
 * @param source Source Node.//from  w  ww. j  av  a  2s  .co  m
 * @param target Target Node.
 */
public static void copyChildNodes(Node source, Node target) {
    AssertArgument.isNotNull(source, "source");
    AssertArgument.isNotNull(target, "target");

    List nodeList = DomUtils.copyNodeList(source.getChildNodes());
    int childCount = nodeList.size();

    for (int i = 0; i < childCount; i++) {
        target.appendChild((Node) nodeList.get(i));
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Replace one node with a list of nodes.
 * @param newNodes New nodes - added in same location as oldNode.
 * @param oldNode Old node - removed./*from   w ww  .java  2 s  . co  m*/
 * @param clone Clone Nodelist Nodes.
 */
public static void replaceNode(NodeList newNodes, Node oldNode, boolean clone) {
    AssertArgument.isNotNull(newNodes, "newNodes");
    AssertArgument.isNotNull(oldNode, "oldNode");

    Node parentNode = oldNode.getParentNode();

    if (parentNode == null) {
        logger.debug("Cannot replace [" + oldNode + "] with a NodeList. [" + oldNode + "] has no parent.");
        return;
    }

    int nodeCount = newNodes.getLength();
    List nodeList = DomUtils.copyNodeList(newNodes);

    if (nodeCount == 0) {
        if (!(parentNode instanceof Document)) {
            parentNode.removeChild(oldNode);
        }
        return;
    }

    if (parentNode instanceof Document) {
        List elements = DomUtils.getElements(newNodes, "*", null);

        if (!elements.isEmpty()) {
            logger.debug(
                    "Request to replace the Document root node with a 1+ in length NodeList.  Replacing root node with the first element node from the NodeList.");
            parentNode.removeChild(oldNode);
            parentNode.appendChild((Node) elements.get(0));
        } else {
            logger.debug(
                    "Cannot replace document root element with a NodeList that doesn't contain an element node.");
        }
    } else {
        for (int i = 0; i < nodeCount; i++) {
            if (clone) {
                parentNode.insertBefore(((Node) nodeList.get(i)).cloneNode(true), oldNode);
            } else {
                parentNode.insertBefore((Node) nodeList.get(i), oldNode);
            }
        }
        parentNode.removeChild(oldNode);
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Insert the supplied node before the supplied reference node (refNode).
 * @param newNode Node to be inserted.// w w w .  j a va2s .  c  om
 * @param refNode Reference node before which the supplied nodes should
 * be inserted.
 */
public static void insertBefore(Node newNode, Node refNode) {
    AssertArgument.isNotNull(newNode, "newNode");
    AssertArgument.isNotNull(refNode, "refNode");

    Node parentNode = refNode.getParentNode();

    if (parentNode == null) {
        logger.debug(
                "Cannot insert [" + newNode + "] before [" + refNode + "]. [" + refNode + "] has no parent.");
        return;
    }

    if (parentNode instanceof Document && newNode.getNodeType() == Node.ELEMENT_NODE) {
        logger.debug(
                "Request to insert an element before the Document root node.  This is not allowed.  Replacing the Document root with the new Node.");
        parentNode.removeChild(refNode);
        parentNode.appendChild(newNode);
    } else {
        parentNode.insertBefore(newNode, refNode);
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Insert the supplied nodes before the supplied reference node (refNode).
 * @param newNodes Nodes to be inserted.
 * @param refNode Reference node before which the supplied nodes should
 * be inserted.//from w  ww  . j  a v a  2  s  . c  om
 */
public static void insertBefore(NodeList newNodes, Node refNode) {
    AssertArgument.isNotNull(newNodes, "newNodes");
    AssertArgument.isNotNull(refNode, "refNode");

    Node parentNode = refNode.getParentNode();

    if (parentNode == null) {
        logger.debug("Cannot insert a NodeList before [" + refNode + "]. [" + refNode + "] has no parent.");
        return;
    }

    int nodeCount = newNodes.getLength();
    List nodeList = DomUtils.copyNodeList(newNodes);

    if (nodeCount == 0) {
        return;
    }

    if (parentNode instanceof Document) {
        List elements = DomUtils.getElements(newNodes, "*", null);

        if (!elements.isEmpty()) {
            logger.debug(
                    "Request to insert a NodeList before the Document root node.  Will replace the root element with the 1st element node from the NodeList.");
            parentNode.removeChild(refNode);
            parentNode.appendChild((Node) elements.get(0));
        } else {
            logger.debug(
                    "Cannot insert beforen the document root element from a NodeList that doesn't contain an element node.");
        }

        for (int i = 0; i < nodeCount; i++) {
            Node node = (Node) nodeList.get(i);
            if (node.getNodeType() != Node.ELEMENT_NODE) {
                System.out.println("****" + node);
                parentNode.insertBefore(node, refNode);
            }
        }
    } else {
        for (int i = 0; i < nodeCount; i++) {
            parentNode.insertBefore((Node) nodeList.get(i), refNode);
        }
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Remove the supplied element from its containing document.
 * <p/>//from www . ja va2s .c  o m
 * Tries to manage scenarios where a request is made to remove the root element.
 * Cannot remove the root element in any of the following situations:
 * <ul>
 *    <li>"keepChildren" parameter is false.</li>
 *    <li>root element is empty of {@link Node#ELEMENT_NODE} nodes.</li>
 * </ul>
 * @param element Element to be removed.
 * @param keepChildren Keep child content.
 */
public static void removeElement(Element element, boolean keepChildren) {
    AssertArgument.isNotNull(element, "element");

    Node parent = element.getParentNode();
    if (parent == null) {
        logger.debug("Cannot remove element [" + element + "]. [" + element + "] has no parent.");
        return;
    }

    NodeList children = element.getChildNodes();

    if (parent instanceof Document) {
        List childElements = null;

        if (!keepChildren) {
            logger.debug("Cannot remove document root element [" + DomUtils.getName(element)
                    + "] without keeping child content.");
        } else {
            if (children != null && children.getLength() > 0) {
                childElements = DomUtils.getElements(element, "*", null);
            }

            if (childElements != null && !childElements.isEmpty()) {
                parent.removeChild(element);
                parent.appendChild((Element) childElements.get(0));
            } else {
                logger.debug("Cannot remove empty document root element [" + DomUtils.getName(element) + "].");
            }
        }
    } else {
        if (keepChildren && children != null) {
            DomUtils.insertBefore(children, element);
        }
        parent.removeChild(element);
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Append the nodes from the supplied list to the supplied node. 
 * @param node Node to be appended to./*from w  ww  .  jav  a  2s .  com*/
 * @param nodes List of nodes to append.
 */
public static void appendList(Node node, List nodes) {
    AssertArgument.isNotNull(node, "node");
    AssertArgument.isNotNull(nodes, "nodes");

    int nodeCount = nodes.size();

    for (int i = 0; i < nodeCount; i++) {
        node.appendChild((Node) nodes.get(i));
    }
}

From source file:org.docx4j.openpackaging.parts.XmlPart.java

/**
 * Set the value of the node referenced in the xpath expression.
 * /*ww  w  .java2 s  .  co  m*/
 * @param xpath
 * @param value
 * @param prefixMappings a string such as "xmlns:ns0='http://schemas.medchart'"
 * @return
 * @throws Docx4JException
 */
public boolean setNodeValueAtXPath(String xpath, String value, String prefixMappings) throws Docx4JException {

    try {
        getNamespaceContext().registerPrefixMappings(prefixMappings);

        Node n = (Node) xPath.evaluate(xpath, doc, XPathConstants.NODE);
        if (n == null) {
            log.debug("xpath returned null");
            return false;
        }
        log.debug(n.getClass().getName());

        // Method 1: Crimson throws error
        // Could avoid with System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
        //       "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        //n.setTextContent(value);

        // Method 2: crimson ignores
        // n.setNodeValue(value);

        // Method 3: createTextNode, then append it
        // First, need to delete/replace existing text node 
        if (n.getChildNodes() != null && n.getChildNodes().getLength() > 0) {
            NodeList nodes = n.getChildNodes();
            for (int i = nodes.getLength(); i > 0; i--) {
                n.removeChild(nodes.item(i - 1));
            }
        }
        Text t = n.getOwnerDocument().createTextNode(value);
        n.appendChild(t);

        // cache is now invalid
        return true;
    } catch (Exception e) {
        throw new Docx4JException("Problem setting value at xpath " + xpath);
    }

}

From source file:org.docx4j.XmlUtils.java

/**
 * @param docBuilder//from  w  w  w . j a v  a 2s.  co m
 *          the parser
 * @param parent
 *          node to add fragment to
 * @param fragment
 *          a well formed XML fragment
* @throws ParserConfigurationException 
 */
public static void appendXmlFragment(Document document, Node parent, String fragment)
        throws IOException, SAXException, ParserConfigurationException {

    Node fragmentNode = XmlUtils.getNewDocumentBuilder().parse(new InputSource(new StringReader(fragment)))
            .getDocumentElement();

    fragmentNode = document.importNode(fragmentNode, true);

    parent.appendChild(fragmentNode);
}