由於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」]'與'*'匹配相同的元素。我不會試圖回答你的問題,因爲這個問題似乎在不斷變化。 –