我是XPath的新手,我有以下问题:
我有一个从webservices接收数据的Java方法,这些数据都在一个XML文档中,所以我必须使用XPath来获取这个XML结果文档中的一个特定值。
特别是,这是我的web服务( web服务响应)提供的整个XML输出:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<getConfigSettingsResponse xmlns="http://tempuri.org/">
<getConfigSettingsResult><![CDATA[<root>
<status>
<id>0</id>
<message></message>
</status>
<drivers>
<drive id="tokenId 11">
<shared-secret>Shared 11</shared-secret>
<encoding>false</encoding>
<compression />
</drive>
<drive id="tokenId 2 ">
<shared-secret>Shared 2 </shared-secret>
<encoding>false</encoding>
<compression>false</compression>
</drive>
</drivers>
</root>]]></getConfigSettingsResult>
</getConfigSettingsResponse>
</s:Body>
</s:Envelope>现在,在Java类中,我执行以下操作:
XPath xPath; // An utility class for performing XPath calls on JDOM nodes
Element objectElement; // An XML element
//xPath = XPath.newInstance("s:Envelope/s:Body/getVersionResponse/getVersionResult");
try {
// XPath selection:
xPath = XPath.newInstance("s:Envelope/s:Body");
xPath.addNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
objectElement = (Element) xPath.selectSingleNode(documentXML);
if (objectElement != null) {
result = objectElement.getValue();
System.out.println("RESULT:");
System.out.println(result);
}
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}打印结果变量内容的结果是这样的输出:
RESULT:
<root>
<status>
<id>0</id>
<message></message>
</status>
<drivers>
<drive id="tokenId 11">
<shared-secret>Shared 11</shared-secret>
<encoding>false</encoding>
<compression />
</drive>
<drive id="tokenId 2 ">
<shared-secret>Shared 2 </shared-secret>
<encoding>false</encoding>
<compression>false</compression>
</drive>
</drivers>
</root>现在我的问题是,我只想访问标记的内容,所以我希望(在本例中)我的结果变量必须包含值。
但我做不到,我已经尝试用以下方法更改以前的XPath选择:
xPath = XPath.newInstance("s:Envelope/s:Body/s:status/s:id");但是这样做,我可以得到我的objectElement是空。
为什么?我遗漏了什么?要获得包含id标记内容的mu结果变量,我要做什么?
Tnx
安德里亚
发布于 2013-11-21 15:47:26
实际上,您应该在JDOM2.x中使用新的XPathAPI,并考虑pasha701的答案,您的代码应该更类似于:
Namespace soap = Namespace.getNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
Namespace tempuri = Namespace.getNamespace("turi", ""http://tempuri.org/");
XPathExpression<Element> xpath = XPathFactory.instance().compile(
"s:Envelope/s:Body/turi:getConfigSettingsResponse/turi:getConfigSettingsResult",
Filters.element(), null, soap, tempuri);
Element result = xpath.evaluateFirst(documentXML);
String resultxml = result.getValue();
Document resultdoc = new SAXBuilder().build(new StringReader(resultxml));
Element id = resultdoc.getRootElement().getChild("status").getChild("id");https://stackoverflow.com/questions/20124558
复制相似问题