我正在尝试做一些我认为非常简单的事情,只需断言 Xpath 节点的属性是一个特定值。该节点没有值,只有一个属性值,如下:-
<ControlResponse Success="true"/>
(将返回“true”或“false”)
<?xml version="1.0" encoding="UTF-8"?><tag0:AAA_ControlRS xmlns:tag0="http://www.xmltravel.com/fab/2002/09" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Target="test" Version="2002A" xsi:type="AAA_ControlRS">
<tag0:TestInfo TestId="THFTEST"/>
<tag0:SessionInfo CreateNewSession="true"/>
<AAASessionId="8IzujBAVOPVQrO1ySpNBoJ9x"/>
<tag0:ControlResponse Success="true"/>
</tag0:AAA_ControlRS>
这是我的代码:
//REQUEST
String controlRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n...
//bunch of xml here";
//RESPONSE
String myControlResponse = given().
when().
request().
contentType("text/xml").
body(myControlRequest).
when().post().andReturn().asString();
//Parse response and get relevant node via Xpath
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource((new StringReader(myControlResponse))));
//Xpath Factory Object
XPathFactory xPathFactory = XPathFactory.newInstance();
//Xpath Object
XPath xpath = xPathFactory.newXPath();
String controlResponse = getNodeValue(doc, xpath);
assertEquals("true", controlResponse);
} catch (ParserConfigurationException | org.xml.sax.SAXException | IOException e) {
e.printStackTrace();
}
}
private static String getNodeValue(Document doc, XPath xpath) {
String controlResponse = null;
try {
XPathExpression expr =
xpath.compile("//ControlResponse/@Success");
controlResponse = (String) expr.evaluate(doc, XPathConstants.STRING);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return controlResponse;
}
当我期望字符串“true”时,xpath 的计算结果为 null。我想实现获取属性值并断言它是否包含字符串“true”或“false”
有没有更简单的方法来实现我想要做的事情?
最佳答案
要获取属性值,请使用//ControlResponse/@Success
作为XPath表达式。
如果命名空间问题妨碍您,请使用 //*[local-name()="ControlResponse"]/@Success
进行快速检查(如果问题与命名空间相关)。
使用不相关示例文档的示例:
> cat ~/test.xml
<root><foo bar="true"/></root>
> xmllint --xpath '//foo/@bar' ~/test.xml
bar="true"
如果这在您的情况下不能按预期工作,请显示足够的 XML 文档以确保问题可以重现。
关于java - 使用 XPathFactory 评估 Xpath 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40722927/