用于获取属性值的 Xpath 表达式在 Java 中失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4186633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:13:39  来源:igfitidea点击:

Xpath expression for getting an attribute value fails in Java

javaxpath

提问by Jonathan

I am trying to get an attribute value from an XML file, but my code fails with the exception below:

我试图从 XML 文件中获取属性值,但我的代码失败并出现以下异常:

11-15 16:34:42.270: DEBUG/XpathUtil(403): exception = javax.xml.xpath.XPathExpressionException: javax.xml.transform.TransformerException: Extra illegal tokens: '@', 'source'

11-15 16:34:42.270: DEBUG/XpathUtil(403): 异常 = javax.xml.xpath.XPathExpressionException: javax.xml.transform.TransformerException: 额外的非法标记: '@', 'source'

Here is the code I use to get the node list:

这是我用来获取节点列表的代码:

private static final String XPATH_SOURCE = "array/extConsumer@source";
mDocument = XpathUtils.createXpathDocument(xml);

NodeList fullNameNodeList = XpathUtils.getNodeList(mDocument,
                XPATH_FULLNAME);

And here is my XpathUtilsclass:

这是我的XpathUtils课:

public class XpathUtils {

    private static XPath xpath = XPathFactory.newInstance().newXPath();
    private static String TAG = "XpathUtil";

    public static Document createXpathDocument(String xml) {
        try {

            Log.d(TAG , "about to create document builder factory");
            DocumentBuilderFactory docFactory = DocumentBuilderFactory
                    .newInstance();
            Log.d(TAG , "about to create document builder ");
            DocumentBuilder builder = docFactory.newDocumentBuilder();

            Log.d(TAG , "about to create document with parsing the xml string which is: ");

            Log.d(TAG ,xml );
            Document document = builder.parse(new InputSource(
                    new StringReader(xml)));

            Log.d(TAG , "If i see this message then everythings fine ");

            return document;
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG , "EXCEPTION OCCURED HERE " + e.toString());
            return null;
        }
    }

    public static NodeList getNodeList(Document doc, String expr) {
        try {
            Log.d(TAG , "inside getNodeList");
            XPathExpression pathExpr = xpath.compile(expr);
            return (NodeList) pathExpr.evaluate(doc, XPathConstants.NODESET);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "exception = " + e.toString());
        }
        return null;
    }

    // extracts the String value for the given expression
    public static String getNodeValue(Node n, String expr) {
        try {
            Log.d(TAG , "inside getNodeValue");
            XPathExpression pathExpr = xpath.compile(expr);
            return (String) pathExpr.evaluate(n, XPathConstants.STRING);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

I get an exception thrown in the getNodeListmethod.

我在getNodeList方法中抛出异常。

Now, according to http://www.w3schools.com/xpath/xpath_syntax.asp, to get an attribute value, you use the "@" sign. But for some reason, Java is complaining about this symbol.

现在,根据http://www.w3schools.com/xpath/xpath_syntax.asp,要获取属性值,请使用“@”符号。但出于某种原因,Java 抱怨这个符号。

回答by vanje

Try

尝试

array/extConsumer/@source

as your XPath expression. This selects the source attribute of the extConsumer element.

作为您的 XPath 表达式。这将选择 extConsumer 元素的源属性。

回答by Anon

Put a slash before the attribute spec:

在属性规范前加一个斜杠:

array/extConsumer/@source

回答by Pops

The w3schools page you linked to also says "Predicates are always embedded in square brackets." You just appended the @source. Try

您链接到的 w3schools 页面也说“谓词总是嵌入在方括号中”。您刚刚附加了@source. 尝试

private static final String XPATH_SOURCE = "array/extConsumer[@source]";

EDIT:
To be clear, this is if you're looking for a single item, which is what your original wording led me to believe. If you want to collect a bunch of source attributes, see the answers by vanje and Anon that suggest using a slash instead of square brackets.

编辑:
要清楚,这是如果您正在寻找单个项目,这就是您的原始措辞让我相信的。如果您想收集一堆源属性,请参阅 vanje 和 Anon 的答案,建议使用斜杠而不是方括号。