java - Selenium 网络驱动程序 : Validate httpResponse xml

标签 java xml-parsing

我想验证从 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/

相关文章:

java - 您是否应该省略已由该类的属性指定的变量名中的信息?

java - org.openqa.selenium.WebDriverException : disconnected: received Inspector. 使用 Selenium 和 Chromedriver 执行测试期间发生分离事件错误

java - 使用 ContentValues 将以零开头的字符串编号插入字符串列,但始终删除前导零

java - Camel CXF客户端 SOAP 故障处理

java - 在 ant 脚本中连接 xml 文件时如何避免 xml header

java - 如何使用 DOM 解析器解析忽略 DOCTYPE 声明的 xhtml

java - 节点对象 - 为空节点对象分配值

java - 你如何判断 unicode 字母在 Java 中是否是连续的?

swift - 使用 XMLParsing swift 库发布请求时出现错误 401

java - 当 XPath 使用 preceding-sibling axis 时,我想以相反的顺序返回节点?如何 ?