简体   繁体   English

Java DOM解析器错误

[英]Java DOM parser error

Here is my xml file: 这是我的xml文件:

<?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: 这是我的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: 这是给我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! 谢谢!

You code looks good. 您的代码看起来不错。

It even does not throw any exception on jdk-7. 它甚至不会在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. document.getElementsByTagName("MaximumUserNumber")返回一个NodeList。 It has a single found node. 它有一个找到的节点。 Each element node (type == ELEMENT_NODE) even if it contains only text has children. 每个元素节点(类型== ELEMENT_NODE)即使仅包含文本也具有子元素。 In this case the only child is a node of type TEXT_NODE: Node textNode = foundNode.getChildNodes().item(0); 在这种情况下,唯一的子节点是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. 在这里, .getTextContent()返回此节点及其后代的文本内容。

Both cases are not really safe (no null checks nor node type checks) but if using with schema may be considered as such. 两种情况都不是真正安全的(没有null检查也没有节点类型检查),但是如果与schema一起使用,则可以认为是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM