简体   繁体   English

Xpath在java中检索节点的属性

[英]Xpath retrieve the attribute of the node in java

I want to retrieve a field with attributes but that doesn't work.我想检索具有属性的字段,但这不起作用。

Here is my xml file这是我的 xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<fields>
    <field name="a" class="b" libelle="zozo"></field>
    <field name="c" class="c" libelle="zaza"></field>
</fields>

The Xpath expression : Xpath 表达式:

//field[@name[.='a'] and @class[.='b']]

The Java code: Java代码:

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.*;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String args[]) throws Exception {
        String fileName = Main.class.getResource("exemple.xml").getFile();
        Document document = getDocument(fileName);
        System.out.println(evaluateXPath(document, "//field[@name='a' and @class='b']")); //updated with the proposition of @Michael 
        System.out.println(evaluateXPath(document, "//field/@name[.='a']")); //to show you that the parser work a bit
    }


    private static Document getDocument(String fileName) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(fileName);
        return doc;
    }

    private static List<String> evaluateXPath(Document document, String xpathExpression){

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        List<String> values = new ArrayList<>();
        try {
            XPathExpression expr = xpath.compile(xpathExpression);
            NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
            if (nodes != null)
                for (int i = 0; i < nodes.getLength(); i++) {
                    if (nodes.item(i).getNodeValue() != null)
                        values.add(nodes.item(i).getNodeValue());
                }
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return values;
    }
}

With this set up I expect to get有了这个设置,我希望得到

<field name="a" class="b" libelle="zozo">

But i don't get anything.但我什么也得不到。 I tried with online Xpath validators and it worked but not in Java..我尝试使用在线 Xpath 验证器,它可以工作,但不能在 Java 中使用。

I saw that it could come from namespace in xml but there is none in mine.我看到它可能来自 xml 中的命名空间,但我的没有。

Thanks for your help谢谢你的帮助

Solution解决方案

As @Alexandra said below, I was using a method that would return null in my case.正如@Alexandra 在下面所说,我使用的方法在我的情况下会返回 null。

In order to retrieve a value from an attribute you have to use :为了从属性中检索值,您必须使用:

nodes.item(0).getAttributes().getNamedItem("YourAttributeName");

Try to change XPath evaluation either to尝试将 XPath 评估更改为

NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

or to或者

Node node = (Node) expr.evaluate(document, XPathConstants.NODE);

depending on how many nodes are expected to be found.取决于预期会找到多少个节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM