Java HTML / XML How to - Convert an XML fragment to string








Question

We would like to know how to convert an XML fragment to string.

Answer

import java.io.File;
import java.io.StringWriter;
//from w ww .  j  a v  a2  s.c o m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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

public class Main {
  public static void main(String[] args) throws Exception {
    File fXmlFile = new File("data.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();
    System.out.println("Root element :"
        + doc.getDocumentElement().getNodeName());
    NodeList nList = doc.getElementsByTagName("Employee");
    for (int temp = 0; temp < nList.getLength(); temp++) {
      System.out.println(nodeToString(nList.item(temp)));
    }
  }
  private static String nodeToString(Node node) throws Exception {
    StringWriter sw = new StringWriter();
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.transform(new DOMSource(node), new StreamResult(sw));
    return sw.toString();
  }
}