【发布时间】:2016-12-02 13:11:22
【问题描述】:
给定xml sn-p:
<AddedExtras>
<AddedExtra Code="1234|ABCD" Quantity="1" Supplier="BDA"/>
<AddedExtra Code="5678|EFGH" Quantity="1" Supplier="BDA"/>
<AddedExtra Code="9111|ZXYW" Quantity="1" Supplier="BDA"/>
</AddedExtras>
以下 XPath 表达式:
//*["AddedExtra"]/@Code
当通过检查器运行时,评估结果为:
Attribute='Code=1234|ABCD'
Attribute='Code=5678|EFGH'
Attribute='Code=9111|ZXYW'
那为什么下面的代码只返回第一行?
private String allCodes = "//*["AddedExtra"]/@Code";
从系统中获取我的 XML 并将其解析为 Doc:
public Document parseResponse(String response){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
//Create a document reader and an XPath object
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource((new StringReader(response))));
} catch (ParserConfigurationException | org.xml.sax.SAXException | IOException e) {
e.printStackTrace();
}
return doc;
}
获取新文档:
public Document getParsedResponse(String response) {
return parseResponse(response);
}
从文档中返回 Xpath 值:
public String getAllCodeOptions(String response){
Document doc = getParsedResponse(response);
return getNodeValueFromNodeList(doc, allCodes);
}
读取 XML 节点的新方法:
public String getNodeValueFromNodeList(Document doc, String expression){
NodeList nodeList = null;
String nodes = null;
try {
nodeList = (NodeList) xpath.compile(expression).evaluate(doc, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
for(int i=0; i < nodeList.getLength(); i++){
Node node = nodeList.item(i);
nodes = node.getNodeValue();
}
return nodes;
}
返回:
Attribute='Code=1234|ABCD'
【问题讨论】:
-
请注意,您的谓词是错误的。非空字符串的有效布尔值为真,因此
*["AddedExtra"]匹配与*相同的元素。我不会试图回答你的问题,因为这个问题似乎在不断变化。
标签: java xml xpath xml-parsing