简体   繁体   English

从Xpath获取属性

[英]Get Attribute from Xpath

I need a method that can give me back the value of a specified attribute inside a specified xpath. 我需要一个方法,可以将指定的xpath中指定属性的值还给我。 So for example if we have xpath = /root/foo/body/part[5]/test[3] and we want the value of the attribute id inside the test[3] tag of the xpath then I need to be able to call a method that looks something like this: 因此,例如,如果我们有xpath = /root/foo/body/part[5]/test[3] ,并且想要在xpath的test[3]标记内包含属性id的值,那么我需要调用看起来像这样的方法:

public String getAttributeValue(String xpath, String attribute) {
     String attributeValue = "xpath/attribute".value();
     return attributeValue;
}

You can try with the @ command 您可以尝试使用@命令

//xpath[@attribute]

Note that you can also filter with the @ 请注意,您也可以使用@过滤

//xpath[@attribute='filtervalue']

Figured it out... 弄清楚了...

public String retrieveAttributeValue(Document document, String xpath, String attribute) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression xPathExpression = xPath.compile(xpath + "/" + attribute);
    String attributeValue = "" + xPathExpression.evaluate(document, XPathConstants.STRING);
    return attributeValue;
}

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

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