gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:06:53 24 4
gpt4 key购买 nike

我有以下 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com