使用Xpath进行属性提取

时间:2017-03-13 06:19:09

标签: java xml xpath

我有一个XML作为Java String:

String abc = "<Tags  Value = '635' Type = 'Number'/>";

我试图使用Xpath

提取这样一个XML对象的Value

我到现在为止尝试的是这样的:

InputSource doc = new InputSource(abc);
XPath xPath =  XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("/Tags[@Value]");
System.out.println(expr.evaluate(doc));

2 个答案:

答案 0 :(得分:1)

 InputSource doc = new InputSource(abc);
 XPath xPath =  XPathFactory.newInstance().newXPath();
 XPathExpression expr = xPath.compile("/Tags/@Value");
 System.out.println(expr.evaluate(doc));

答案 1 :(得分:1)

试试吧

public class Example {

    public static void main(String[] args) throws FileNotFoundException, XPathExpressionException {
        String abc = "<Tags  Value = '635' Type = 'Number'/>";
        InputSource doc = new InputSource(new StringReader(abc));
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xPath.compile("/Tags/@Value");
        System.out.println(expr.evaluate(doc)); // 635
    }

}