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

Extracting attribute values from an HttpResponse XML in Java

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

我正在使用 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);

谢谢

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

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