Andrey Yaskulsky
Andrey Yaskulsky

Reputation: 2516

Java DOM parser error

Here is my xml file:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE Server SYSTEM "Server.dtd">
<Server>
    <MaximumUserNumber>2</MaximumUserNumber>
    <ServerPortNumber>1234</ServerPortNumber>
    <MessagesQueueSize>5</MessagesQueueSize>
</Server>

here is my Server.dtd:

<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT Server 
         (MaximumUserNumber,
          ServerPortNumber,
          MessagesQueueSize)>
<!ELEMENT MaximumUserNumber (#PCDATA)>
<!ELEMENT ServerPortNumber (#PCDATA)>
<!ELEMENT MessagesQueueSize (#PCDATA)>

Here is my code that gives me a NullPointerException:

    public Server() {
        try {

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setValidating(true);
            Document document = dbf.newDocumentBuilder().parse("config.xml");
            document.normalizeDocument();
            NodeList nl = document.getElementsByTagName("MaximumUserNumber");
            nl.item(0); // this line causes exception

          }
}

What I'm doing wrong? Thanks!

Upvotes: 0

Views: 1179

Answers (1)

Vitaly
Vitaly

Reputation: 2790

You code looks good.

It even does not throw any exception on jdk-7. Perhaps, you did not include the code that does.

You just did not do one more step in finding the value of the element:

    NodeList nodeList = document.getElementsByTagName("MaximumUserNumber");
    Node foundNode = nodeList.item(0);
    Node textNode = foundNode.getChildNodes().item(0);
    String value = textNode.getNodeValue();
    System.out.println(value);

Output

2

Explanation

document.getElementsByTagName("MaximumUserNumber") return a NodeList. It has a single found node. Each element node (type == ELEMENT_NODE) even if it contains only text has children. In this case the only child is a node of type TEXT_NODE: Node textNode = foundNode.getChildNodes().item(0);. From the node of this type you just get its value.

There is a quicker way to get the text value from the text only element:

    NodeList nodeList = document.getElementsByTagName("MaximumUserNumber");
    Node foundNode = nodeList.item(0);
    String value = foundNode.getTextContent();
    System.out.println(value);

Here, .getTextContent() returns the text content of this node and its descendants.

Both cases are not really safe (no null checks nor node type checks) but if using with schema may be considered as such.

Upvotes: 1

Related Questions