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:DomUtils.java

/**
 * Remove the supplied element from its containing document.
 * <p/>/*from  w w w  . java 2 s  .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) {

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

    NodeList children = element.getChildNodes();

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

        if (!keepChildren) {
            System.out.println("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 {
                System.out.println(
                        "Cannot remove empty document root element [" + DomUtils.getName(element) + "].");
            }
        }
    } else {
        if (keepChildren && children != null) {
            DomUtils.insertBefore(children, element);
        }
        parent.removeChild(element);
    }
}

From source file:com.fiorano.openesb.application.aps.InPortInst.java

/**
 *  Returns the xml string equivalent of this object.
 *
 * @param document the input Document object
 * @return element node/*from w  ww. j a  v a2 s . c o  m*/
 * @exception FioranoException if an error occurs while creating the element
 *      node.
 */
public Node toJXMLString(Document document) throws FioranoException {
    Node root0 = document.createElement("InPortInst");

    ((Element) root0).setAttribute("isSyncRequestType", "" + isSyncRequestType());
    ((Element) root0).setAttribute("isDisabled", "" + isDisabled());

    Node child = null;

    child = XMLDmiUtil.getNodeObject("Name", m_strPortName, document);
    if (child != null) {
        root0.appendChild(child);
    }

    if (!StringUtils.isEmpty(m_strDscription)) {
        child = XMLDmiUtil.getNodeObject("Description", m_strDscription, document);
        if (child != null) {
            root0.appendChild(child);
        }
    }
    if (m_strXSDRef != null) {
        child = XMLDmiUtil.getNodeObject(PortInstConstants.PORT_XSDREF, m_strXSDRef, document);
        root0.appendChild(child);
    }

    if (!StringUtils.isEmpty(m_strJavaClass)) {
        child = XMLDmiUtil.getNodeObject("JavaClass", m_strJavaClass, document);
        if (child != null) {
            root0.appendChild(child);
        }
    }
    if (m_params != null && m_params.size() > 0) {
        Enumeration _enum = m_params.elements();

        while (_enum.hasMoreElements()) {
            Param param = (Param) _enum.nextElement();
            if (!StringUtils.isEmpty(param.getParamName()) && !StringUtils.isEmpty(param.getParamValue())) {
                if (!checkIfDefaultValue(param.getParamName(), param.getParamValue())) {
                    Node paramNode = param.toJXMLString(document);
                    root0.appendChild(paramNode);
                }
            }
        }
    }

    return root0;
}

From source file:cc.siara.csv_ml.ParsedObject.java

/**
 * Performas any pending activity against an element to finalize it. In this
 * case, it adds any pending attributes needing namespace mapping.
 * /* w  ww.  jav  a2 s  . co  m*/
 * Also if the node has a namespace attached, it recreates the node with
 * specific URI.
 */
public void finalizeElement() {
    // Add all remaining attributes
    for (String col_name : pendingAttributes.keySet()) {
        String value = pendingAttributes.get(col_name);
        int cIdx = col_name.indexOf(':');
        String ns = col_name.substring(0, cIdx);
        String nsURI = nsMap.get(ns);
        if (nsURI == null)
            nsURI = generalNSURI;
        Attr attr = doc.createAttributeNS(nsURI, col_name.substring(cIdx + 1));
        attr.setPrefix(ns);
        attr.setValue(value);
        ((Element) cur_element).setAttributeNodeNS(attr);
    }
    // If the element had a namespace prefix, it has to be recreated.
    if (!currentElementNS.equals("") && !doc.getDocumentElement().equals(cur_element)) {
        Node parent = cur_element.getParentNode();
        Element cur_ele = (Element) parent.removeChild(cur_element);
        String node_name = cur_ele.getNodeName();
        String nsURI = nsMap.get(currentElementNS);
        if (nsURI == null)
            nsURI = generalNSURI;
        Element new_node = doc.createElementNS(nsURI, currentElementNS + ":" + node_name);
        parent.appendChild(new_node);
        // Add all attributes
        NamedNodeMap attrs = cur_ele.getAttributes();
        while (attrs.getLength() > 0) {
            Attr attr = (Attr) attrs.item(0);
            cur_ele.removeAttributeNode(attr);
            nsURI = attr.getNamespaceURI();
            new_node.setAttributeNodeNS(attr);
        }
        // Add all CData sections
        NodeList childNodes = cur_ele.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node node = childNodes.item(i);
            if (node.getNodeType() == Node.CDATA_SECTION_NODE)
                new_node.appendChild(node);
        }
        cur_element = new_node;
    }
    pendingAttributes = new Hashtable<String, String>();
}

From source file:DOMProcessor.java

/** Adds text as the child of the given node.
  * @param text Text to add to node./*from  www .ja  v a2 s . c om*/
  * @param node Element to attach text.
  */
public void addText(String text, Node node) {
    node.appendChild(dom.createTextNode(text));
}

From source file:eu.europa.esig.dss.xades.signature.XAdESSignatureBuilder.java

/**
 * This method creates a new instance of Signature element.
 *//*from   w ww. j a  va  2 s .  c o  m*/
public void incorporateSignatureDom() {
    signatureDom = documentDom.createElementNS(XMLNS, DS_SIGNATURE);
    signatureDom.setAttribute(XMLNS_DS, XMLNS);
    signatureDom.setAttribute(ID, deterministicId);

    final Node parentNodeOfSignature = getParentNodeOfSignature();
    parentNodeOfSignature.appendChild(signatureDom);
}

From source file:com.fiorano.openesb.application.aps.ApplicationContext.java

/**
 *  Returns the xml string equivalent of this object.
 *
 * @param document the input Document object
 * @return element node/*from www.j a v  a  2 s.c  o m*/
 * @exception FioranoException if an error occurs while creating the element
 *      node.
 * @since Tifosi2.0
 */
Node toJXMLString(Document document) throws FioranoException {
    Node root0 = document.createElement("ApplicationContext");

    Node node;

    if (!StringUtils.isEmpty(m_structure)) {
        Element elem = document.createElement("Structure");
        CDATASection cdata = document.createCDATASection(m_structure);

        elem.appendChild(cdata);
        root0.appendChild(elem);
    }

    if (!StringUtils.isEmpty(m_defaultInstance)) {
        node = XMLDmiUtil.getNodeObject("DefaultInstance", m_defaultInstance, document);
        if (node != null)
            root0.appendChild(node);
    }

    if (!StringUtils.isEmpty(m_rootElement)) {
        node = XMLDmiUtil.getNodeObject("RootElement", m_rootElement, document);
        if (node != null)
            root0.appendChild(node);
    }

    if (!StringUtils.isEmpty(m_rootElementNamespace)) {
        node = XMLDmiUtil.getNodeObject("RootElementNamespace", m_rootElementNamespace, document);
        if (node != null)
            root0.appendChild(node);
    }

    node = XMLDmiUtil.getNodeObject("StructureType", String.valueOf(m_structureType), document);
    if (node != null)
        root0.appendChild(node);

    return root0;
}

From source file:de.fhg.iais.asc.xslt.binaries.DownloadAndScale.java

Node apply(Node binaries) {
    Node result = this.targetDoc.createDocumentFragment();

    NodeList children = binaries.getChildNodes();

    int length = children.getLength();
    for (int i = 0; i < length; ++i) {
        Node item = children.item(i);

        String itemName = item.getNodeName();

        try {//from   www . j  av  a  2 s  .c  o m
            if (itemName.equals(ELEMNAME_SET_PARAMS)) {
                handleSetParameters(item);
            } else if (itemName.equals(ELEMNAME_BINARY)) {
                List<Node> nodes = handleBinary(item);
                for (Node resultBinary : nodes) {
                    result.appendChild(resultBinary);
                }
            }
        } catch (AscTechnicalErrorException e) {
            if (this.ascContext.get(AscConfiguration.BINARIES_CONTINUE_ON_FAIL, false)) {
                continue;
            } else {
                throw e;
            }
        }
    }

    this.parameters.clear();

    return result;
}

From source file: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  w w .  j  a v  a2 s .  c  om*/
 * @param clone Clone Nodelist Nodes.
 */
public static void replaceNode(NodeList newNodes, Node oldNode, boolean clone) {

    Node parentNode = oldNode.getParentNode();

    if (parentNode == null) {
        System.out
                .println("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()) {
            System.out.println(
                    "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 {
            System.out.println(
                    "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:com.adaptris.util.XmlUtils.java

/**
 * Convenience method which appends a new Node to the children of a parent
 *
 * @param newNode the Node to be added//  ww w  .  jav  a 2 s. c  o  m
 * @param parent the parent Node
 * @throws Exception on error.
 */
public void appendNode(Node newNode, Node parent) throws Exception {
    Document parentDoc = parent.getOwnerDocument();
    Document newDoc = newNode.getOwnerDocument();

    if (!parentDoc.equals(newDoc)) {
        newNode = parentDoc.importNode(newNode, true);
    }

    parent.appendChild(newNode);
}

From source file:de.betterform.xml.xforms.model.Instance.java

public void createNode(List nodeset, int position, String qname) throws XFormsException {
    if (nodeset.size() < position) {
        return;//from   w  ww  .j a  va  2  s .c  om
    }

    Node parentNode = (Node) ((NodeWrapper) nodeset.get(position - 1)).getUnderlyingNode();
    try {
        parentNode.appendChild(createElement(qname));
    } catch (DOMException e) {
        throw new XFormsBindingException(e.getMessage(), this.target, null);
    }
}