gpt4 book ai didi

java - Java从xml中获取特定属性值

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

我正在尝试使用 Java 解析以下 XML。

    <connection inherit="true" name="test">
<ConnectionDetails>
<conn name="domainname1.net">
<prop name="dom-test" tags="1-test, con"/>
</conn>
<conn name="domainname2.net">
<prop name="dom-test" tags="2-test, con"/>
</conn>
<conn name="domainname3.net">
<prop name="dom-org" tags="org, con"/>
</conn>
<conn name="domainname4.net">
<prop name="dom-test" tags="3-test"/>
</conn>
<conn name="domainname5.net">
<prop name="dom-org" tags="org"/>
</conn>
</ConnectionDetails>
</connection>

我编写了如下 Java 代码:

File inputFile = new File("test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("conn");

我需要的是:

  • To get all connection with tag that contains the text "test" - domainname1.net, domainname2.net, domainname4.net

请帮忙!

最佳答案

您可以使用 XPath:

XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression query = xPath.compile("//prop[contains(@tags, 'test')]/../@name");
NodeList nList = (NodeList)query.evaluate(doc, XPathConstants.NODESET);

如果您更喜欢更手动的方法(或者您不希望 XPath 的开销),您可以这样做:

NodeList nList = doc.getElementsByTagName("prop");
for (int i = 0, len = nList.getLength(); i < len; i++) {
Element elm = (Element)nList.item(i);
if (elm.getAttribute("name").contains("test")) {
String connName = ((Element)elm.getParentNode()).getAttribute("name");
// ...
}
}

关于java - Java从xml中获取特定属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37851266/

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