Java 验证XML元素标记

Java 验证XML元素标记,java,Java,我有一个XML文件,比如 <parent> <child1> <child2> <name>name</name> <value> <item>value></item> </value> </child2> </child1> <child1> <value>

我有一个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");
                }
}
File xmlfile=新文件(“sample.xml”);
DocumentBuilderFactory dbfaFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder DocumentBuilder=dbfaFactory.newDocumentBuilder();
Document doc=documentBuilder.parse(xmlfile);
nodelistchild1=doc.getElementsByTagName(“child1”);
对于(int i=0;i

谢谢。

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

要么尝试使用<代码> Posi1.GETelEngsByTAGNEAR(“Health2”)< /C> >,要么考虑使用“明智”的XML库。XOM例如具有一种按预期的方式工作的功能。


编辑:正如Jenson所指出的,您可能会遇到带有null check子句的
NullPointerException
s,请使用
child1.getElementsByTagName(“child2”)!=null

您可能会发现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());
        }
作为XPath表达式。如果您只想计算
child1
具有非
child2
子级的次数,则可以使用:

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

if条件适用于child1而非child2。if(!doc.getElementsByTagName(“child1”).equals(null))不确定这是否会导致nullpointer异常(null.equals)原因child1可能为空。但是,您的代码永远不会检测到第二个
child1
元素缺少其
child2
元素,相反,它将只打印第一个
child2
元素。您可能需要编写更复杂的XPath表达式,或者需要放弃XPath并坚持使用DOM。请编辑答案带有一些XPath表达式选项,可以捕获不同的信息。
/parent/child1/*[not(self::child2)][1]