我想验证从 httpResponse 获取的 XML 响应
我的代码
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(decouplingURL);
httpPost.setEntity(new StringEntity(soapRequest));
System.out.println(soapRequest);
HttpResponse httpResponse = httpclient.execute(httpPost);
System.out.println(httpResponse);
String resp = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
System.out.println(resp);
String payload = "";
NodeList nl = doc.getElementsByTagName("payload");
for (int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
payload = nameElement.getFirstChild().getNodeValue().trim();
}
}
在上面的代码中,我收到以下响应,我想获取 @status 并验证天气它的值是否为 1。 同样,我必须验证天气“charge-method”是否为 3
<?xml version='1.0' encoding='UTF-8'?>
<er-response>
<payload>
<subscription id="33517965" status="1">
<pricepoint id="package:aceklpackage">
<charge-method>3</charge-method>
<rate resource="EUR" tax-rate="0.23">30.0</rate>
<user-group>hover32</user-group>
</pricepoint>
</subscription>
</payload>
</<er-response>
最佳答案
不确定这个问题与 WebDriver 有什么关系,您正在使用 Apache HttpClient。您可以简单地使用 XPath从 xml 中提取所需的元素:
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resp.getBytes("UTF-8")));
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.printf("Status: %s\n", xPath.evaluate("//subscription/@status", doc));
System.out.printf("Charge Method: %s\n", xPath.evaluate("//charge-method//text()", doc));
结果:
Status: 1
Charge Method: 3
关于java - Selenium 网络驱动程序 : Validate httpResponse xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54162609/