I'm making a webservice call in my Java code and getting the response as String with the below data.
<DocumentElement>
<ResultSet>
<Response>Successfully Sent.</Response>
<UsedCredits>1</UsedCredits>
</ResultSet>
</DocumentElement>
Now, I want to parse the below response String and get the value of <Response>
tag alone for further processing. Since, I'm getting only the CDATA content how to parse the String content?
You obviously need XML parser for this one. Lets say the above is stored in a String
variable named content
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(content)); //content variable holding xml records
Document doc = db.parse(is)
/* Now retrieve data from xml */
NodeList nodes = doc.getElementsByTagName("ResultSet");
Element elm = (Element) nodes.item(0); //will get you <Response> Successfully Sent.</Response>
String responseText = elm.getFirstChild().getNodeValue();
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
Follow the above parser routine for larger data sets. Use loops for multiple similar data sets. Hope that helps.