Xpath - 为什么只返回1个值?

时间:2016-12-02 13:11:23

标签: java xml xpath xml-parsing

给出xml片段:

<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);
}

从doc:

返回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'

2 个答案:

答案 0 :(得分:1)

您需要使用正确的evaluate方法,该方法将返回类型作为参数。如下所示,

NodeSet result = (NodeSet)e.evaluate(e, doc, XPathConstants.NODESET); 
for(int index = 0; index < result.getLength(); index ++) 
{      
  Node node = result.item(index);
  String name = node.getNodeValue();
}

答案 1 :(得分:0)

问题是你只要求一个值。

试试这个:

NodeList nodeList = (NodeList)e.evaluate(doc, XPathConstants.NODESET);

表示多个值。

有关教程,请参阅http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/