7

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?

Ted
  • 127
  • 1
  • 2
  • 9
  • for me the [KSOAP2](http://ksoap2.sourceforge.net/) is one of the best ways to handle this kind of responses – mihail Aug 15 '12 at 14:55

2 Answers2

9

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

su-
  • 3,116
  • 3
  • 32
  • 42
  • Thanks for the response, this does work the only problem is when I use my actual response it doesn't. I think it does this because the string contains quotes that are not escaped properly. – Ted Aug 15 '12 at 17:30
  • I'm not sure what exactly you get in the response, one guess is that it may include BOM (google XML BOM for more info) in the beginning of UTF string. If you have a debugger (like the one in Eclipse), it should be pretty straight forward to figure out what the difference between it and a hardcoded working string. – su- Aug 15 '12 at 18:54
  • If the response's text encoding is UTF-8, maybe it's also worth a try to change response = EntityUtils.toString(resEntity); to response = EntityUtils.toString(resEntity, "UTF-8"); – su- Aug 15 '12 at 18:59
1

1. Use the DOM Parser.

Eg:

DocumentBuilderFactory odbf = DocumentBuilderFactory.newInstance();
 DocumentBuilder odb =  odbf.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(xml));
            Document odoc = odb.parse(is);
            odoc.getDocumentElement().normalize ();    // normalize text representation
            System.out.println ("Root element of the doc is " + odoc.getDocumentElement().getNodeName());
            NodeList LOP = odoc.getElementsByTagName("locations");
            int totalPersons =LOP.getLength();
            System.out.println("Total nos of locations:"+totalPersons);

            for(int s=0; s<LOP.getLength() ; s++)
            {
                Node FPN =LOP.item(s);
                if(FPN.getNodeType() == Node.ELEMENT_NODE)
                    {

                    Element latlon = (Element)FPN;                                                                

                    NodeList oNameList1 = latlon.getElementsByTagName("featured");                                       
                    Element firstNameElement = (Element)oNameList1.item(0);
                    NodeList textNList1 = firstNameElement.getChildNodes();
                    //this.setLocationId(((Node)textNList1.item(0)).getNodeValue().trim());    
                    featuredArr = changeToBoolean(((Node)textNList1.item(0)).getNodeValue().trim());                                    // value taken
                    System.out.println("#####The Parsed data#####");
                    System.out.println("featured : " + ((Node)textNList1.item(0)).getNodeValue().trim());           
                    System.out.println("#####The Parsed data#####");
     }

See this link for more details:

http://tutorials.jenkov.com/java-xml/dom.html

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75