Java HTML / XML How to - Create XML document using nodeList








Question

We would like to know how to create XML document using nodeList.

Answer

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
//from  w w  w.  j a  v  a2 s.c o  m
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;

public class Main {
  public static void main(String[] args) throws Exception {
    String exp = "/configs/markets/market";
    String path = "data.xml";

    Document xmlDocument = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().parse(path);

    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression xPathExpression = xPath.compile(exp);
    NodeList nodes = (NodeList) xPathExpression.evaluate(xmlDocument,
        XPathConstants.NODESET);

    Document newXmlDocument = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().newDocument();
    Element root = newXmlDocument.createElement("root");
    newXmlDocument.appendChild(root);
    for (int i = 0; i < nodes.getLength(); i++) {
      Node node = nodes.item(i);
      Node copyNode = newXmlDocument.importNode(node, true);
      root.appendChild(copyNode);
    }
    printXmlDocument(newXmlDocument);
  }

  public static void printXmlDocument(Document document) {
    DOMImplementationLS domImplementationLS = (DOMImplementationLS) document
        .getImplementation();
    LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
    String string = lsSerializer.writeToString(document);
    System.out.println(string);
  }
}