Учитывая 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 "]' соответствует тем же элементам, что и '*'. Я не собираюсь пытаться ответить на ваш вопрос, потому что вопрос, похоже, постоянно меняется. –