java 从 Xpath 获取属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14478142/
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
Get Attribute from Xpath
提问by ThreaT
I need a method that can give me back the value of a specified attribute inside a specified 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 中指定属性的值。因此,例如,如果我们有xpath = /root/foo/body/part[5]/test[3]
并且我们想要xpath 标签id
内的属性值,test[3]
那么我需要能够调用一个看起来像这样的方法:
public String getAttributeValue(String xpath, String attribute) {
String attributeValue = "xpath/attribute".value();
return attributeValue;
}
采纳答案by ThreaT
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;
}
回答by BigMike
You can try with the @
command
您可以尝试使用@
命令
//xpath[@attribute]
Note that you can also filter with the @
请注意,您还可以使用 @
//xpath[@attribute='filtervalue']