0
我試圖做一件相當簡單的事情,我認爲,只是斷言Xpath節點的屬性是特定的值。該節點有沒有價值,分析:定冠詞的屬性值,如下所示: - <ControlResponse Success="true"/>
(將返回「真」或「假」)使用XPathFactory評估Xpath屬性
<?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;
}
中的XPath計算結果爲當我期望字符串「真」時爲null。我想實現獲取屬性值並斷言它是否包含字符串「true」或「false」
是否有更簡單的方法來實現我正在嘗試執行的操作?
謝謝,我更新了代碼,但XPath表達式評估爲null? – Steerpike
@Steerpike更新了答案...可能你的輸入XML有命名空間嗎? – Markus
謝謝。我對命名空間並不確定,但我只是google了一下,我認爲你是正確的。我發佈了我希望解析的完整XML響應(此XML作爲響應發送)。我正在使用RestAssurred(嘗試)並可能能夠使用該庫處理名稱空間? – Steerpike