简体   繁体   English

从Java中的HttpResponse XML提取属性值

[英]Extracting attribute values from an HttpResponse XML in Java

So I've gotten help from here already so I figured why not try it out again!? 所以我已经从这里得到了帮助,所以我想出了为什么不再次尝试它呢? Any suggestions would be greatly appreciated. 任何建议将不胜感激。

I'm using HTTP client and making a POST request; 我正在使用HTTP客户端并发出POST请求; the response is an XML body that looks like the following: 响应是一个如下所示的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>    

Now... 现在...

I have an HttpEntity which is 我有一个HttpEntity

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

i would like to get the value of <pass count="0" /> from the xml response through java code. 我想通过Java代码从xml响应中获取<pass count="0" />的值。 can some one help me pls ? 有人可以帮我吗?

Detail code i made but getting null pointer exception. 我编写的详细代码,但得到空指针异常。

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

Thanks 谢谢

Please note the pass and fail are empty tags (the tags closed as /> ) and they do not hold any value. 请注意, passfail是空标记(标记以/>闭合),它们不包含任何值。 If you are trying to extract the value of the count attribute, you can try the following 如果您尝试提取count属性的值,则可以尝试以下操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM