0

我有一个 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");
                }
}

但是每次我得到 Not Equal to null 时,即使 XML 中缺少 child2 节点。

这里 child2 不见了

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

谢谢。

4

2 回答 2

1

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

要么尝试使用child1.getElementsByTagName("child2"),要么考虑使用“健全”的 XML 库。例如,XOM 有一个getChildElements(String name)按您期望的方式工作的功能。

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

于 2012-08-03T12:02:46.960 回答
0

您可能会发现 XPath 非常适合此任务:

    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(new File("sample.xml"));

        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();
        XPathExpression xPathExpression = xPath.compile("/parent/child1/child2");

        NodeList nodeList = (NodeList) xPathExpression.evaluate(document, XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            System.out.println(node.getNodeName());
        }

如果child2存在,则nodeList.getLength()等于 1(或 下的child2元素数child1),否则为零。

如果您想要所有child1没有孩子的实例,child2您可以使用:

/parent/child1/*[not(self::child2)]

作为您的 XPath 表达式。如果您只想计算child1没有孩子的次数,child2那么您可以使用:

/parent/child1/*[not(self::child2)][1]
于 2012-08-03T12:19:50.303 回答