0

我要做的只是从 XML 文件中读取一行。除了空值,我似乎什么都得不到。我想直接从文档中读取会话 ID,而不需要创建大量代码。必须有一种超级简单的方法。

<loginResponse>
   <status message="Success" code="Success"/>
   <sessionid>d713868c-608b-440f-a708-5b7055e2e8d2</sessionid>
</loginResponse>


            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();
            String xmlString = EntityUtils.toString(r_entity);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(xmlString));
            Document doc = db.parse(inStream);


            doc.getDocumentElement().normalize();
            NodeList nodeLst = doc.getElementsByTagName("sessionid");
            Node node = nodeLst.item(0);
            String sessionID = node.getTextContent();

            mDbHelper.createAccount(userName, password, sessionID);
4

1 回答 1

1

最简单的方法是使用 Scanner 类。

Scanner scan = new Scanner(stream);
while (scan.hasNextLine()) {
    String line = scan.nextLine();
    if(line.startsWith("\t<sessionid>"))
    {
        System.out.println(line.substring("\t<sessionid>".length()));
    }
 }
于 2013-03-19T23:43:13.830 回答