【问题标题】:Extracting attribute values from an HttpResponse XML in Java从 Java 中的 HttpResponse XML 中提取属性值
【发布时间】:2017-04-25 19:05:30
【问题描述】:

所以我已经从这里得到了帮助,所以我想为什么不再试一次!?任何建议将不胜感激。

我正在使用 HTTP 客户端并发出 POST 请求;响应是一个如下所示的 XML 正文:

    <?xml version="1.0" encoding="UTF-8"?>
<invokeResult>
<method name="RS">
<params>
      <param name="sp" value="" />
      <param name="cp" value="" />
      <param name="ck" value="" />
 </params>
 </method>
 <status>OK</status>
 <result>
    <status>ENDED</status>
    <reportUrl></reportUrl>
    <runId></runId>
    <pass count="0" />
    <fail count="1" />
    <message>column,report</message>
  </result>
</invokeResult>    

现在...

我有一个 HttpEntity

String responseString = EntityUtils.toString(response.getEntity()); 

我想通过 java 代码从 xml 响应中获取 &lt;pass count="0" /&gt; 的值。有人可以帮我吗?

我制作的详细代码但出现空指针异常。

DefaultHttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("REQUEST-URL");
        HttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == 200 && response.getEntity() != null) { 
            String responseString = EntityUtils.toString(response.getEntity());
            responseString=responseString.replaceAll("<?xml*?>", "").trim();
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new InputSource(new StringReader(
                    responseString)));
            NodeList orderNode = doc.getElementsByTagName("<pass count=");
            String strOrdNo = orderNode.item(0).getTextContent();
            logger.info("pass Value = " + strOrdNo);

谢谢

【问题讨论】:

  • 你在哪一行得到 NPE?
  • 我在 NodeList orderNode = doc.getElementsByTagName("
    你只需要在那里传递标签名称; doc.getElementsByTagName("pass")。请在下面查看我的答案。

标签: java xml dom xml-parsing httpresponse


【解决方案1】:

请注意passfail 是空标签(标签关闭为/&gt;),它们不包含任何值。如果您尝试提取count 属性的值,可以尝试以下操作

NodeList orderNode = doc.getElementsByTagName("pass");
String strOrdNo = orderNode .item(0).getAttributes().getNamedItem("count").getNodeValue();
logger.info("pass Value = " + strOrdNo);

【讨论】:

  • 太棒了。我现在得到了价值。非常感谢先生。
猜你喜欢
  • 2021-03-27
  • 2019-10-15
  • 2013-01-18
  • 1970-01-01
  • 2021-09-24
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多