如何使用jdom检查文件中是否存在元素

时间:2011-07-11 09:38:29

标签: java xml jdom

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

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

List children = root.getChildren("Achild");
int size = children.size();

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

答案 2 :(得分: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();
    }