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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With