Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse xml from httppost response

During the execution of a http POST i store the response as a String response.

HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
response = EntityUtils.toString(resEntity);

If I print response it looks like:

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

I would like to store just the sessionID as a string. I've tried

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

and various methods like this but it won't let me run the code since DocumentBuildFactory and InputSource are invalid.

What should I be doing to extract specific strings from this XML?

like image 862
Ted Avatar asked Aug 15 '12 14:08

Ted


1 Answers

This is just quick and dirty test. It worked for me.

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) {
        }
    }
}

output: lo8mdn7bientr71b5kn1kote90

like image 95
su- Avatar answered Sep 24 '22 00:09

su-