Create a DOM tree from XML document in Java
Description
The following code shows how to create a DOM tree from XML document.
Example
/* w ww .j a va2 s. c o m*/
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
public class Main {
public static void main(String[] argv) throws Exception {
StringReader sr = new StringReader("<tag>java2s.com</tag>");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder loader = factory.newDocumentBuilder();
Document document = loader.parse(new InputSource(sr));
System.out.println(document);
Element tree = document.getDocumentElement();
System.out.println(tree);
}
}
The code above generates the following result.