由于XML片段:Xpath - 为什么只返回1个值?
<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并将其解析到一个文件:
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'
见http://stackoverflow.com/questions/2811001/how-to-read-xml-using-xpath-in-java – pringi
请注意,你的断言是错误的。非空字符串的有效布尔值为true,因此'* [“AddedExtra”]'与'*'匹配相同的元素。我不会试图回答你的问题,因为这个问题似乎在不断变化。 –