简体   繁体   English

使用Xpath提取属性

[英]attribute extraction using Xpath

I have an XML as Java String: 我有一个XML作为Java String:

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

I am trying to extract the Value of such an XML object using Xpath 我正在尝试使用Xpath提取此类XML对象的Value

What I tried until now is something like this: 到目前为止,我一直在尝试以下内容:

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

try it 试试吧

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
    }

}

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

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