【问题标题】:Xpath - why only 1 value returned?Xpath - 为什么只返回 1 个值?
【发布时间】: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


【解决方案1】:

您需要使用正确的评估方法,该方法将返回类型作为参数。像下面这样,

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

【讨论】:

    【解决方案2】:

    问题是您只要求一个值。

    试试这个:

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

    用于多个值。

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

    【讨论】:

      猜你喜欢
      • 2019-12-21
      • 2011-12-12
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 2021-10-28
      相关资源
      最近更新 更多