从Java中的HttpResponse XML中提取属性值

时间:2017-04-25 19:05:30

标签: java xml dom xml-parsing httpresponse

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

我正在使用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响应中获取<pass count="0" />的值。有人可以帮我吗?

我制作的详细代码,但是获得空指针异常。

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);

由于

1 个答案:

答案 0 :(得分:0)

请注意,passfail是空标记(标记关闭为/>)并且它们不包含任何值。如果您尝试提取count属性的值,可以尝试以下

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