java - java xpath表达式仅在子节点不同时获取值
问题描述
如果子节点与我的表达式中存在的不同,我想获得一个特定的节点值:
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>
例如,我只想获取id
子节点是否'pmc'
为其他节点。
解决方案
由于问题并不完全清楚,让我们这样尝试。
假设您的 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>
并且您正在尝试获取具有子节点<id>
的任何节点的属性值,请尝试使用以下作为您的 xpath 表达式:<type>
<pmc>
//*/type[pmc]/@id
推荐阅读
- spring - javax.inject.Inject bean 在 Spring 引导中无法识别
- c - 为什么当我在它之前/之后有 printf() 时,“malloc():损坏的最大尺寸”错误得到修复?
- php - 无法连接主机:80:超时 cURL php
- c++ - C++ 和 wxWidgets DLL 创建和使用微软访问
- javascript - 如何自动在每周更改的网页上插入特定日期?
- node.js - Mongoose 过滤器嵌套数组
- java - 如何从spring-boot jar BOOT-INF\lib 文件夹中提取文件
- javascript - 是的,验证是字符串或字符串数组
- android - 尝试在推送通知单击时打开片段。不工作
- php - 使用 Zizaco Entrust 实现角色和权限