Tyler64dd
Tyler64dd

Reputation: 1

how to use parse xml android

All I want to do is simply read one line out of an XML file. I cant seem to get anything but null. I want to just read the session id right out of the document without creating massive amounts of code. There has to be a super simple way that works.

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

Upvotes: 0

Views: 146

Answers (1)

sarnabtech
sarnabtech

Reputation: 496

Easiest way to do this is use Scanner class.

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

Upvotes: 1

Related Questions