Java XML Element Root createRootElement(Document doc, String rootTagName)

Here you can find the source of createRootElement(Document doc, String rootTagName)

Description

Create an root element with the specified name

License

Apache License

Parameter

Parameter Description
doc a parameter
rootTagName a parameter

Declaration

public static Element createRootElement(Document doc, String rootTagName) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**//w w w . j  a  v a2 s. com
     * Create an root element with the specified name
     *
     * @param doc
     * @param rootTagName
     * @return
     */
    public static Element createRootElement(Document doc, String rootTagName) {
        if (doc.getDocumentElement() == null) {
            Element root = doc.createElement(rootTagName);
            doc.appendChild(root);
            return root;
        }
        return doc.getDocumentElement();
    }

    /**
     * Create an element with the specified name
     *
     * @param parent
     * @param tagName
     * @return
     */
    public static Element createElement(Element parent, String tagName) {
        Document doc = parent.getOwnerDocument();
        Element child = doc.createElement(tagName);
        parent.appendChild(child);
        return child;
    }

    /**
     * create an child element with the specified name and value and append it in a parent element
     *
     * @param parent
     * @param tagName
     * @param value
     * @return
     */
    public static Element createElement(Element parent, String tagName, String value) {
        Document doc = parent.getOwnerDocument();
        Element child = doc.createElement(tagName);
        setElementValue(child, value);
        parent.appendChild(child);
        return child;
    }

    /**
     * Set the value of element
     *
     * @param element
     * @param val
     */
    public static void setElementValue(Element element, String val) {
        Node node = element.getOwnerDocument().createTextNode(val);
        NodeList nl = element.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node nd = nl.item(i);
            if (nd.getNodeType() == Node.TEXT_NODE) {
                nd.setNodeValue(val);
                return;
            }
        }
        element.appendChild(node);
    }
}

Related

  1. createRoot(Document document, String title)
  2. createRootElement(Document doc, String name)
  3. createRootElement(Document doc, String name)
  4. getElement(String elementName, Node rootNode)
  5. getElementData(final Element root, final String elementName)
  6. getElementData(final Element root, final String elementName)
  7. getElementText(String elemName, Element root, boolean trim)