java使用XPathFactory评估Xpath属性
我试着做一些非常简单的事情,我想,简单地断言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”
有没有更简单的方法来实现我的目标
# 1 楼答案
要获取属性值,请使用
//ControlResponse/@Success
作为XPath表达式如果名称空间问题妨碍了您,请使用
//*[local-name()="ControlResponse"]/@Success
快速检查问题是否与名称空间有关使用不相关示例文档的示例:
如果这在您的案例中没有达到预期效果,请显示足够多的XML文档,说明问题是可重现的