gpt4 book ai didi

java - 验证 XML 元素标记

转载 作者:行者123 更新时间:2023-12-01 15:14:42 24 4
gpt4 key购买 nike

我有一个类似于

的 XML 文件
<parent>
<child1>
<child2>
<name>name</name>
<value>
<item>value></item>
</value>
</child2>
</child1>
<child1>
<value>
<item>value></item>
</value>
</child1>
</parent>

这里我需要检查child2节点是否丢失。

我的java代码就像

File xmlfile = new File ("sample.xml");
DocumentBuilderFactory dbfaFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = dbfaFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(xmlfile);
NodeList child1= doc.getElementsByTagName("child1");
for( int i=0; i<child1.getLength(); i++)
{
NodeList child1= doc.getElementsByTagName("child1");
if(!doc.getElementsByTagName("child2").equals(null))
{
System.out.println("Not Equal to null");

else
{
System.out.println("Equal to null");
}
}

但每次我得到的结果不等于 null,即使 XML 中缺少 child2 节点。

此处缺少 child2

<child1>
<value>
<item>value></item>
</value>
</child1>

谢谢。

最佳答案

此代码无法工作:doc.getElementsByTagName("child2") 遍历整个 XML,即它返回它可以找到的任何 child2。

尝试使用 child1.getElementsByTagName("child2"),或者考虑使用“健全的”XML 库。例如,XOM 有一个函数 getChildElements(String name)它按照您期望的方式工作。

编辑:正如 Jenson 所指出的,您可能会遇到带有 null 检查子句的 NullPointerException,请改用 child1.getElementsByTagName("child2") != null

关于java - 验证 XML 元素标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11794608/

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