Java Dom 解析器报告错误的子节点数

标签 java xml dom children

我有以下 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<users>
<user id="0" firstname="John"/>
</users>

然后我试图用 java 解析它,但是 getchildnodes 报告错误的子节点数。

Java代码:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(this.file);
document.getDocumentElement().normalize();
Element root = document.getDocumentElement();
NodeList nodes = root.getChildNodes();
System.out.println(nodes.getLength());

结果:3

此外,我还收到了访问节点属性的 NPE,所以我猜是出了什么大问题。

最佳答案

子节点由空白元素和文本节点组成。在处理属性之前,您需要检查节点类型。您可能还想考虑使用从 Java SE 5 开始的 JDK/JRE 中可用的 javax.xml.xpath API。

示例 1

此示例演示如何针对 DOM 发出 XPath 语句。

package forum11649396;

import java.io.StringReader;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        String xml = "<?xml version='1.0' encoding='UTF-8'?><users><user id='0' firstname='John'/></users>";

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(new InputSource(new StringReader(xml)));

        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        Element userElement = (Element) xpath.evaluate("/users/user", document, XPathConstants.NODE);
        System.out.println(userElement.getAttribute("id"));
        System.out.println(userElement.getAttribute("firstname"));
    }

}

示例 2

以下示例演示了如何针对 InputSource 发出 XPath 语句以获取 DOM 节点。这使您不必自己将 XML 解析为 DOM。

package forum11649396;

import java.io.StringReader;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        String xml = "<?xml version='1.0' encoding='UTF-8'?><users><user id='0' firstname='John'/></users>";

        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        InputSource inputSource = new InputSource(new StringReader(xml));
        Element userElement = (Element) xpath.evaluate("/users/user", inputSource, XPathConstants.NODE);
        System.out.println(userElement.getAttribute("id"));
        System.out.println(userElement.getAttribute("firstname"));
    }

}

关于Java Dom 解析器报告错误的子节点数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11649396/

相关文章:

javascript - 为什么 `getComputedStyle` 不为 anchor 标记返回 "inline"?

javascript - 拦截网页上的任何网络事件?

java - 缓存映射器输出

java - 使用 Java 代码使用 JMeter JMX 脚本运行测试片段时出现问题

Java 标识符需要分号,给出 : Variable naming conventions

android - Android Studio 中 NFC 技术过滤器不支持的类型技术列表

android - "ArrayAdapter requires the resource ID to be a TextView"XML问题

php - UPS 运输教程 (PHP)

javascript - 在某些浏览器中,转义的 html 字符未被 jquery .html() 转义

java - 如何将时间戳转换为几天前