gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:52:49 25 4
gpt4 key购买 nike

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

关于java - 如何使用 jdom 检查文件中是否存在元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6648271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com