繁体   English   中英

从Xpath获取属性

[英]Get Attribute from Xpath

我需要一个方法,可以将指定的xpath中指定属性的值还给我。 因此,例如,如果我们有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;
}

您可以尝试使用@命令

//xpath[@attribute]

请注意,您也可以使用@过滤

//xpath[@attribute='filtervalue']

弄清楚了...

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