java从具有相同名称标记的xml文件中检索所需的数据
我在服务器上发布了一些csv输入文件,它会给我一个xml文件,如下所示:
<ns0:TransportationEvent xmlns:ns0="http://www.server.com/schemas/TransportationEvent.xsd">
<ns0:deviceId>4567289456</ns0:deviceId>
.....
.....
</ns0:TransportationEvent>
<ns0:TransportationEvent xmlns:ns0="http://www.server.com/schemas/TransportationEvent.xsd">
<ns0:deviceId>7965145741</ns0:deviceId>
.....
.....
</ns0:TransportationEvent>
<ns0:TransportationEvent xmlns:ns0="http://www.server.com/schemas/TransportationEvent.xsd">
<ns0:deviceId>2168744654</ns0:deviceId>
.....
.....
</ns0:TransportationEvent>
TransportationEvent标签将一次又一次地添加,其中包含更新的设备ID
我使用XpathFactory类和NamespaceContext类从这个xml中检索数据,如下所示:
NamespaceContext ctx = new NamespaceContext() {
public String getNamespaceURI(String prefix) {
String uri;
if (prefix.equals("ns0"))
uri = "http://www.server.com/schemas/TransportationEvent.xsd";
else
uri = null;
return uri;
}
public Iterator getPrefixes(String val) {
return null;
}
// Dummy implementation - not used!
public String getPrefix(String uri) {
return null;
}
};
XPathFactory xpathFact = XPathFactory.newInstance();
XPath xpath = xpathFact.newXPath();
xpath.setNamespaceContext(ctx);
String strXpath = "//ns0:TransportationEvent/ns0:deviceId/text()";
String deviceId = xpath.evaluate(strXpath, doc);
上述代码给出了deviceId的值为4567289456。基本上,它总是从第一个TransportationEvent标记获取值
我需要从“TransportationEvent”标记中选取数据,其中“deviceId”等于我选择的deviceId。比如:
String strXpath = "//ns0:TransportationEvent[where ns0:deviceId = " + myDeviceId + "]/ns0:deviceId/text()";
我可以通过使用NodeList类来实现这一点,并可以遍历所有“TransportationEvent”标记,但这样我就无法使用Xpath或NamespaceContext实现。我发现NodeList类和NamespaceContext类或Xpath类之间没有联系
我想得到ctx的值,该值包含所需的TransportationEvent标记的上下文
我知道我错过了什么。有人能帮忙吗
# 1 楼答案
您可以获取感兴趣的设备ID的父节点,如下所示:
//ns0:deviceId[text()='7965145741']/parent::node()
这就是输出: