App下載
首頁javadomJava HTML/XML - 如何從XML文檔獲取根元素

Java HTML/XML - 如何從XML文檔獲取根元素

我們想知道如何從XML文檔獲取根元素。
   
import java.io.StringReader;

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();
    System.out.println(e);
  }

}