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

/**
 * Automatically set text in a Node. Basically we find the first
 * Text node beneath the current node and replace it with a
 * CDATASection for the incoming text. All other Text nodes are
 * removed. Throws a DOMException if it's illegal to add a Text
 * child to the particular node.//from w ww .  j  av  a  2s. c  o  m
 *
 * @param node the starting node for the search.
 * @param text the text to be set
 * @param allowMarkupInText whether to allow markup in text to pass through unparsed
 * @return the updated node
 * @throws DOMException if the Text object is not found
 */
public static Node setTextInNode(Node node, String text, boolean allowMarkupInText) {
    //start by setting the value in the first text node we find with a comment
    Comment comment = node.getOwnerDocument().createComment("");
    Node newNode = null;

    //csc_092701.1 - support both encoded/unencoded text
    if (allowMarkupInText)
        newNode = node.getOwnerDocument().createCDATASection(text);
    else
        newNode = node.getOwnerDocument().createTextNode(text);
    //System.out.println ("newNode: "+newNode);

    Text textComp = DOMUtil.findFirstText((Element) node);
    //System.out.println ("textComp:"+textComp);        
    if (textComp == null) {
        node.appendChild(comment);
    } else {
        Node parent = textComp.getParentNode();
        parent.replaceChild(comment, textComp);
    }

    //now remove all the rest of the text nodes
    removeAllTextNodes(node);

    //now replace the comment with the newNode
    Node parent = comment.getParentNode();
    parent.replaceChild(newNode, comment);
    //System.out.println ("parent:  "+parent);        
    //System.out.println ("result:  "+DOMUtil.findFirstText((Element) parent));        
    //DOMUtil.printStackTrace(parent.getOwnerDocument().getDocumentElement());
    return node;
}

From source file:com.evolveum.midpoint.prism.xml.XmlTypeConverter.java

public static void appendBelowNode(Object val, QName xsdType, QName name, Node parentNode, boolean recordType)
        throws SchemaException {
    Object xsdElement = toXsdElement(val, xsdType, name, parentNode.getOwnerDocument(), recordType);
    if (xsdElement == null) {
        return;/*ww w .  j a  va  2 s  .c  om*/
    }
    if (xsdElement instanceof Element) {
        parentNode.appendChild((Element) xsdElement);
        //        } else if (xsdElement instanceof JAXBElement) {
        //            try {
        //                JAXBUtil.marshal(xsdElement, parentNode);
        //            } catch (JAXBException e) {
        //                throw new SchemaException("Error marshalling element " + xsdElement + ": " + e.getMessage(), e);
        //            }
    } else {
        throw new IllegalStateException("The XSD type converter returned unknown element type: " + xsdElement
                + " (" + xsdElement.getClass().getName() + ")");
    }
}

From source file:com.ephesoft.dcma.util.XMLUtil.java

/**
 * To append Leaf Child./*from  w ww.  j a va  2  s .c  o  m*/
 * 
 * @param doc Document
 * @param parent Node
 * @param childName String
 * @param childData String
 */
public static void appendLeafChild(Document doc, Node parent, String childName, String childData) {
    Element child = doc.createElement(childName);
    if (childData != null && childData.length() != 0) {
        Text text = doc.createTextNode(childData);

        child.appendChild(text);
    }
    parent.appendChild(child);
}

From source file:com.amalto.core.storage.hibernate.DefaultStorageClassLoader.java

private static void addEvent(Document document, Node sessionFactoryElement, String eventType,
        String listenerClass) {//  www  .ja v a2  s . c  o  m
    Element event = document.createElement("event"); //$NON-NLS-1$
    Attr type = document.createAttribute("type"); //$NON-NLS-1$
    type.setValue(eventType);
    event.getAttributes().setNamedItem(type);
    {
        Element listener = document.createElement("listener"); //$NON-NLS-1$
        Attr clazz = document.createAttribute("class"); //$NON-NLS-1$
        clazz.setValue(listenerClass);
        listener.getAttributes().setNamedItem(clazz);
        event.appendChild(listener);
    }
    sessionFactoryElement.appendChild(event);
}

From source file:com.betfair.testing.utils.cougar.assertions.AssertionUtils.java

private static void doDomSorting(Document doc, XPath xpath, String x)
        throws XPathExpressionException, IOException {
    NodeList parentNodes = (NodeList) xpath.evaluate(x, doc, XPathConstants.NODESET);
    for (int i = 0; i < parentNodes.getLength(); i++) {
        Node n = parentNodes.item(i);
        List<Node> allKids = new ArrayList<>(n.getChildNodes().getLength());
        for (int j = n.getChildNodes().getLength() - 1; j >= 0; j--) {
            allKids.add(n.removeChild(n.getFirstChild()));
        }/*from   ww  w  .  java2 s. c o  m*/
        final Map<Node, String> kidsToString = new HashMap<>();

        for (Node k : allKids) {
            kidsToString.put(k, toString(k));
        }
        Collections.sort(allKids, new Comparator<Node>() {
            @Override
            public int compare(Node o1, Node o2) {
                return kidsToString.get(o1).compareTo(kidsToString.get(o2));
            }
        });
        for (Node k : allKids) {
            n.appendChild(k);
        }
    }
}

From source file:fr.ece.epp.tools.Utils.java

public static void updatePom(String path, String[] repo, boolean outOrno) {
    Document document = null;/*  w ww  .j av a  2  s.com*/
    try {
        document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path);
        Element root = document.getDocumentElement();
        Node repositories = root.getElementsByTagName("repositories").item(0);
        for (int i = 0; i < repo.length; i++) {
            Element repository = document.createElement("repository");

            Element id = document.createElement("id");
            id.appendChild(document.createTextNode("repository" + i));
            repository.appendChild(id);

            Element layout = document.createElement("layout");
            layout.appendChild(document.createTextNode("p2"));
            repository.appendChild(layout);

            Element url = document.createElement("url");
            url.appendChild(document.createTextNode(repo[i]));

            repository.appendChild(url);
            repositories.appendChild(repository);
        }
        output(root, path);
        if (outOrno) {
            output(root, null);
        }

    } catch (SAXException e) {
    } catch (IOException e) {
    } catch (ParserConfigurationException e) {
    }
}

From source file:it.cnr.icar.eric.server.common.Utility.java

/**
 * This is an implementation of the JAXP DOM Node.setTextContent
 * method, which does not exist in JDK 1.4. This code was adapted
 * from the Apache Xerces 2.8.0 implementation of this method.
 *///ww  w.  jav  a2  s.com
public static void setTextContent(Node node, String textContent) throws DOMException {
    Node child;

    // get rid of any existing children
    while ((child = node.getFirstChild()) != null) {
        node.removeChild(child);
    }

    // create a Text node to hold the given content
    if (textContent != null && textContent.length() != 0) {
        node.appendChild(node.getOwnerDocument().createTextNode(textContent));
    }
}

From source file:Main.java

private static void convert(Node toCopy, Node saveTo, Document doc) {
    Node newNode;//w  w  w  . j a v  a2  s  .c  om
    switch (toCopy.getNodeType()) {
    case Node.ELEMENT_NODE:
        Element newElement = doc.createElementNS(toCopy.getNamespaceURI(), toCopy.getNodeName());
        newNode = newElement;
        Element baseElement = (Element) toCopy;
        NamedNodeMap children = baseElement.getAttributes();
        for (int i = 0; i < children.getLength(); i++) {
            convertAttribute((Attr) children.item(i), newElement, doc);
        }
        break;
    case Node.TEXT_NODE:
        newNode = doc.createTextNode(toCopy.getTextContent());
        break;
    default:
        newNode = null;
    }
    if (newNode != null) {
        NodeList children = toCopy.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            convert(children.item(i), newNode, doc);
        }

        saveTo.appendChild(newNode);
    }
}

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  w w w. ja va 2 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;
}

From source file:eu.semaine.util.XMLTool.java

/**
 * Create a child element with the given name and append it below node.
 * The new element will have the same namespace as node.
 * If node has a namespace prefix, the new element will also use that namespace prefix.
 * @param node/*from   w  w w. j a v  a 2 s  .  c o  m*/
 * @param childName
 * @return the child element
 */
public static Element appendChildElement(Node node, String childName) {
    if (node == null)
        throw new NullPointerException("Received null node");
    if (childName == null)
        throw new NullPointerException("Received null childName");
    Element child = (Element) node
            .appendChild(createElement(node.getOwnerDocument(), childName, node.getNamespaceURI()));
    String parentPrefix = node.getPrefix();
    if (parentPrefix != null) {
        child.setPrefix(parentPrefix);
    }
    return child;
}