我有一个像这样的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<RootElement>
 <Achild>
  .....
 </Achild>
 </RootElement>


如何检查文件是否包含Achild元素?

            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    // Use the factory to create a builder
    try {
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document doc = builder.parse(configFile);
        final Node parentNode = doc.getDocumentElement();
        final Element childElement = (Element) parentNode.getFirstChild();
                    if(childElement.getNodeName().equalsIgnoreCase(....


但是它给我关于childElement的错误为null ....

最佳答案

SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File("foo.xml"));

XPath xPath = XPath.newInstance("/RootElement/Achild");

/*If you want to find all the "Achild" elements
and do not know what the document structure is,
use the following XPath instead(less efficient):
XPath xPath = XPath.newInstance("//Achild");
*/

Element aChild = (Element) xPath.selectSingleNode(document);

if(aChild == null){
  //There is at least one "Achild" element in the document
} else{
  //No "Achild" elements found
}

09-11 18:53