这是xml
<?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns:processRequestResponse xmlns:ns="http://service.soap.oneflexi.com"><ns:return>
<?xml version="1.0" encoding="UTF-8"?>
<ItemRs language="SG" currency="SGD">
<Items>
<Item>
<CategoryCode />
<CategoryDescription />
<ItemCode>356</ItemCode>
<ItemDescription>20% offer, Latest model</ItemDescription>
<Quantity />
<UnitPrice>24560</UnitPrice>
<ItemBigImagesURL>http://goo.gl/klCGG4</ItemBigImagesURL>
<ItemContent>Front Loading Washing Machine 6.5Kg Capacity 6 Motion Direct Drive</ItemContent>
<ErrorCode />
<ErrorMessage />
<Beaconid>2499</Beaconid>
</Item>
</Items>
<MID />
</ItemRs>
</ns:return>
</ns:processRequestResponse>
</soapenv:Body>
</soapenv:Envelope>
我想验证路径 ItemRs 标记
<ItemRs language="SG" currency="SGD">
我的java代码是
Node result = (Node)xPath.evaluate(" Soapenv:Envelope/Soapenv:Body/ns:processRequestResponse/ns:return/ItemRs[language=\"SG\"]", doc, XPathConstants.NODE);
但是上面的代码不起作用,因为我认为到达节点的路径是错误的。 请提供任何帮助,并提前致谢。
更新
跑完后我得到这个错误
Namespace with prefix 'ns' has not been declared.
是什么意思
答案 0 :(得分:0)
您需要定义从名称空间前缀到URL的映射,并将这些映射添加到上下文中。您可以通过实现NamespaceContext接口来完成此操作。
public class MyNamespaceContext implements NamespaceContext {
private final Map<String, String> PREFIX_MAP = new HashMap<String, String>();
public SimpleNamespaceContext(final Map<String, String> prefixMap) {
PREFIX_MAP.putAll(prefixMap);
}
public String getNamespaceURI(String prefix) {
return PREFIX_MAP.get(prefix);
}
public String getPrefix(String uri) {
throw new UnsupportedOperationException();
}
public Iterator getPrefixes(String uri) {
throw new UnsupportedOperationException();
}
}
这是如何使用这个类。
HashMap<String, String> namespacesByPrefix = new HashMap<String, String>();
namespacesByPrefix.put("ns", "http://service.soap.oneflexi.com");
namespacesByPrefix.put("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
MyNamespaceContext namespaces = new MyNamespaceContext(namespacesByPrefix);
xPath.setNamespaceContext(namespaces);
//...
Node result = (Node)xPath.evaluate("Soapenv:Envelope/Soapenv:Body/ns:processRequestResponse/ns:return/ItemRs[language=\"SG\"]", doc, XPathConstants.NODE);
答案 1 :(得分:0)
我得到了解决方案。我们应该使用xpath作为&#34; // ItemRs&#34;
Node result = (Node)xPath.evaluate("//ItemRs[language=\"SG\"]", doc, XPathConstants.NODE);