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

时间:2010-11-15 16:39:04

标签: java xpath

我正在尝试从XML文件中获取属性值,但我的代码失败,但下面有例外:

  

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

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

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

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

这是我的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;
    }

我在getNodeList方法中抛出异常。

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

3 个答案:

答案 0 :(得分:6)

尝试

array/extConsumer/@source

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

答案 1 :(得分:1)

在属性规范之前加上斜杠:

array/extConsumer/@source

答案 2 :(得分:1)

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

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

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