2

我有一个这样的 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....

4

3 回答 3

1
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
}
于 2011-07-11T11:15:17.253 回答
0
列出孩子 = root.getChildren("Achild");
int size = children.size();

现在检查它是否包含任何孩子的大小。

于 2011-07-11T09:50:55.797 回答
0

在您的代码中,您只是在创建一个构建器,但是它构建了什么?你没有'指定用于创建 DOM 树的文件......下面是一个使用 JDom 的小例子......但是进行搜索和更多的 XPATH 和 XQuery 非常棒......

    try {
        SAXBuilder builder = new SAXBuilder();
        File XmlFile = new File("Xml_File_Path");
        docXml = builder.build(XmlFile.getPath());
        Element root = docXml.getRootElement();
        if (root.getChildren("aChild") == Null)
            do_whateva_you_want
        else
            great_i_can_keep_up

    } catch (JDOMException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
于 2011-07-12T06:34:04.200 回答