Reading Data From Response Which Is In Xml
I am developing an application, in that I have read data which I will get from respose in xml format. So how can implement it. I am not developing web app in my side. But retrievi
Solution 1:
Create a class XMLfunctions
publicclassXMLfunctions {
publicfinalstatic Document XMLfromString(String xml){
Documentdoc=null;
DocumentBuilderFactorydbf= DocumentBuilderFactory.newInstance();
try {
DocumentBuilderdb= dbf.newDocumentBuilder();
InputSourceis=newInputSource();
is.setCharacterStream(newStringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
returnnull;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
returnnull;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
returnnull;
}
return doc;
}
/** Returns element value
* @param elem element (it is XML tag)
* @return Element value otherwise empty String
*/publicfinalstatic String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return"";
}
publicstatic String getTopNewsXML(){
Stringline=null;
try {
DefaultHttpClienthttpClient=newDefaultHttpClient();
HttpPosthttpPost=newHttpPost("url");
HttpResponsehttpResponse= httpClient.execute(httpPost);
HttpEntityhttpEntity= httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
String st= ParseXMLNode(line,"doc");
return st;
}
publicstatic String ParseXMLNode(String str,String node){
StringxmlRecords= str;
Stringresults="";
String[] result = newString [10];
StringBuffersb=newStringBuffer();
try {
DocumentBuilderFactorydbf= DocumentBuilderFactory.newInstance();
DocumentBuilderdb= dbf.newDocumentBuilder();
InputSourceis=newInputSource();
is.setCharacterStream(newStringReader(xmlRecords));
Documentdoc= db.parse(is);
NodeListnlist= doc.getElementsByTagName(node);
sb.append("<results count=");
sb.append("\"10\"");
sb.append(">\r\n");
for (inti=0; i < nlist.getLength(); i++) {
Nodenode1= nlist.item(i);
if (node1.getNodeType() == Node.ELEMENT_NODE) {
Elementelement= (Element) node1;
NodeListnodelist= element.getElementsByTagName("str");
Elementelement1= (Element) nodelist.item(0);
NodeListtitle= element1.getChildNodes();
System.out.print((title.item(0)).getNodeValue());
sb.append("<result>\r\n");
sb.append("<title>");
sb.append(title.item(0).getNodeValue().trim());
sb.append("</title>\r\n");
sb.append("</result>\r\n");
result[i] = title.item(0).getNodeValue();
}
}
sb.append("</results>");
} catch (Exception e) {
System.out.println("Exception........"+results );
e.printStackTrace();
}
return sb.toString();
}
}
publicstaticintnumResults(Document doc) {
Noderesults= doc.getDocumentElement();
intres= -1;
try {
res = Integer.valueOf(results.getAttributes().getNamedItem("count")
.getNodeValue());
} catch (Exception e) {
res = -1;
}
return res;
}
publicstatic String getValue(Element item, String str) {
NodeListn= item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}
in your activity
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getTopNewsXML();
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
Log.d(LOG_TAG, "Number of Results: " + numResults);
if ((numResults <= 0)) {
Toast.makeText(ParentActivity.this, "No Result Found",Toast.LENGTH_LONG).show();
returnnull;
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nodes.item(i);
map.put("title", XMLfunctions.getValue(e, "title"));
mylist.add(map);
}
return mylist;
Then you can put the data in the list
Solution 2:
You can use the built-in DOM parser.
Link: http://developer.android.com/reference/javax/xml/parsers/DocumentBuilder.html
Tutorial: http://www.ibm.com/developerworks/opensource/library/x-android/#list9
Solution 3:
For a comfortable parsing look at
Post a Comment for "Reading Data From Response Which Is In Xml"