Search code examples
javaxmlnulldocumentgetelementsbytagname

Java dom document.getElementsByTagName("") returns null?


I've got a xml as below:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<bookshelf>
    <book ISBN="a01" press="AD press"/>
    <book ISBN="a11" press="BC press">
        <book>JavaSE</book>
        <Author>John</Author>
        <price>35.00</price>
    </book>
    <book ISBN="b11" press="XY press">
        <book>Android</book>
        <Author>Smith</Author>
        <price>35.00</price>
    </book>
</bookshelf>

And a simple Java dom program as below:

    System.out.println(currentPath);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(currentPath + "/book.xml");
    Node node = document.getElementsByTagName("").item(1);
    System.out.println(node);

(1) It prints out "null", why?

(2) I've googled and find many sample code to call document.getElementsByTagName(""), I wish to know if "" stands for root element or sth else?

Thanks a lot.


Solution

  • (1) It prints out "null", why? tag name ("") is empty. please provide the any suitable tag name ("book") included with given xml file

    (2) for get name of the root element. this is a return name of the root element

    document.getDocumentElement().getNodeName();