繁体   English   中英

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

[英]How can I use jdom to check wether an element is present in a file or not

我有一个像这样的 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
}
List children = root.getChildren("Achild");
int size = children.size();

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

在您的代码中,您只是在创建一个构建器,但是它构建了什么? 你没有'指定用于创建 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();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM