【问题标题】:XPath Parser java redundancyXPath Parser java冗余
【发布时间】:2016-03-20 13:57:01
【问题描述】:

所以我需要用 XPath 解析一个 XML 文件。 一切正常,但如果我有一个标签出现多次,我的代码会显示标签内所有相同标签的所有子标签。 例如:我有一个

<a>
  <b></b>
</a>
<c></c>
<a>
  <b></b>
</a>

输出将是:

a
 b
 b
c
a
 b
 b

我的代码是这样的:

 public void parseFileXPath() throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document doc = documentBuilder.parse(file);
    doc.getDocumentElement().normalize();

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    String expression;
    Node node;
    NodeList nodeList;

    expression="/*";
    node = (Node) xpath.evaluate(expression,doc, XPathConstants.NODE);
    //System.out.println(node.getNodeName());

    expression="/frogans-fsdl/*";
    nodeList = (NodeList) xpath.evaluate(expression,doc, XPathConstants.NODESET);


    NodeList nodeList1;


    for (int i = 0; i < nodeList.getLength(); i++) {
        String aTag = nodeList.item(i).getNodeName();

        System.out.println(aTag);
        expression="/frogans-fsdl/"+aTag+"/*";
        nodeList1 = (NodeList) xpath.evaluate(expression,doc,XPathConstants.NODESET);

        for (int j = 0; j < nodeList1.getLength(); j++) {

            System.out.println("\t"+nodeList1.item(j).getNodeName());
            //TODO
            //Display what's inside each tag
        }

        expression="";
    }



}

有什么帮助吗?

【问题讨论】:

    标签: java xml xpath xml-parsing


    【解决方案1】:

    以下内部循环代码可能有助于您想要的输出:

        NodeList nodeList1;
    
        for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.println(nodeList.item(i).getNodeName());
            expression="*";
            nodeList1 = (NodeList) xpath.evaluate(expression,nodeList.item(i),XPathConstants.NODESET);
            for (int j = 0; j < nodeList1.getLength(); j++) {
                System.out.println("\t"+nodeList1.item(j).getNodeName());
            }
        }
    

    基本上,您需要将 nodeList.item(i) 作为第二个参数传递给后续 xpath 评估。

    【讨论】:

      【解决方案2】:

      您的第一个 xath 找到了 frogans-fsdl 的所有子代。这可能是a,c,a 使用您的第二个 xpaht /frogans-fsdl/a/*",您将再次查看 /frogans-fsdl/a/、/frogans-fsdl/c/ 和 /frogans-fsdl/a/ 的所有子项的整个文档。

      您应该将第二个 xpaht 更改为 * 并使用 nodeList.item(i) 作为第二个评估调用的上下文节点。

      【讨论】:

      • 是的,我是从 Mahesh 的回复中得知的,我太笨了,没想到我正在重新解析整个文件。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      相关资源
      最近更新 更多