[英]Get value by xPath knowing only the child of another node - selenium
[英]java xpath expression get only value if child node is different
如果子节点与我的表达式中存在的不同,我想获得节点的一个特定值:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(new File("test.xml"));
List<String> data = new ArrayList<>();
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xpath.evaluate("/name1/type/*[name()!= 'pmc']", document, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Element el = (Element) nodes.item(i);
data.add(el.getAttribute("id"));
}
System.out.println(data);
测试.xml:
<?xml version="1.0" encoding="UTF-8"?>
<name1>
<type id ="1">
<coord>67</coord>
<lmc>57657</lmc>
</type>
<lang>
<eng>989</eng>
<spa>123</spa>
</lang>
</name1>
<name2>
<type id ="2">
<coord>534</coord>
<lmc>654654</lmc>
</type>
<lang>
<eng>354</eng>
<spa>2424</spa>
</lang>
</name2>
<name3>
<type>
<coord>23432</coord>
<pmc>14324</pmc>
</type>
<lang>
<eng>141</eng>
<spa>142</spa>
</lang>
</name3>
例如,如果 childnode 是'pmc'
而不是其他人,我只想获得id
。
既然问题不完全清楚,让我们这样试试。
假设您的 xml 如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<name1>
<type id ="1">
<coord>67</coord>
<lmc>57657</lmc>
</type>
<lang>
<eng>989</eng>
<spa>123</spa>
</lang>
</name1>
<name2>
<type id ="2">
<coord>534</coord>
<lmc>654654</lmc>
</type>
<lang>
<eng>354</eng>
<spa>2424</spa>
</lang>
</name2>
<name3>
<type id ="3">
<coord>23432</coord>
<pmc>14324</pmc>
</type>
<lang>
<eng>141</eng>
<spa>142</spa>
</lang>
</name3>
并且您正在尝试获取具有<pmc>
子节点的任何<type>
节点的属性<id>
的值,请尝试使用以下作为您的 xpath 表达式:
//*/type[pmc]/@id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.