Java HTML / XML How to - Get Root Element in a DOM Document








Question

We would like to know how to get Root Element in a DOM Document.

Answer

import java.io.StringReader;
/*from w  ww. ja v a  2s.c  om*/
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><img/><x></x></a>";
  }
  
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(getXMLData())));

    Element root = doc.getDocumentElement();
    System.out.println(root);
  }
}

The code above generates the following result.