加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 从httppost响应中解析xml

发布时间:2020-12-14 05:58:22 所属栏目:Java 来源:网络整理
导读:在执行http POST期间,我将响应存储为String响应. HttpResponse httpresponse = httpclient.execute(httppost);HttpEntity resEntity = httpresponse.getEntity();response = EntityUtils.toString(resEntity); 如果我打印响应,它看起来像: ?xml version="1.
在执行http POST期间,我将响应存储为String响应.
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
response = EntityUtils.toString(resEntity);

如果我打印响应,它看起来像:

<?xml version="1.0" encoding="UTF-8"?>
<response status="ok">
<sessionID>lo8mdn7bientr71b5kn1kote90</sessionID>
</response>

我想将sessionID存储为字符串.我试过了

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));

和这样的各种方法,但它不会让我运行代码,因为DocumentBuildFactory和InputSource是无效的.

我应该怎么做才能从这个XML中提取特定的字符串?

解决方法

这只是快速而肮脏的测试.它对我有用.
import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Test {
    public static void main(String[] args) {
        String xml= "<?xml version="1.0" encoding="UTF-8"?><response status="ok"><sessionID>lo8mdn7bientr71b5kn1kote90</sessionID></response>";
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        InputSource is;
        try {
            builder = factory.newDocumentBuilder();
            is = new InputSource(new StringReader(xml));
            Document doc = builder.parse(is);
            NodeList list = doc.getElementsByTagName("sessionID");
            System.out.println(list.item(0).getTextContent());
        } catch (ParserConfigurationException e) {
        } catch (SAXException e) {
        } catch (IOException e) {
        }
    }
}

输出:lo8mdn7bientr71b5kn1kote90

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读