Java HTML / XML How to - Get root element from XML document


We would like to know how to get root element from XML document.


   // ww w .  j  a  va2 s . co m

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 String getXMLData() {
    return "<a><person  number='' dept=''><name>myName</name></person></a>";

  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document document = factory.newDocumentBuilder().parse(
        new InputSource(new StringReader(getXMLData())));

    Element e = document.getDocumentElement();


The code above generates the following result.