问题
I'm new to XML parsing and want to convert XML file resulting from a web service to list of POJOs. as i have done some work with JSon and found it very easy to work with. while in the case of XML there is quiet same process but i cant find way of traversing through the Hierarchy and reaching a specific node to be parsed to POJO. As i explain my question with example . here is response in XML format
<hash>
<resp_status>1</resp_status>
<message>success</message>
<errors></errors>
<calendars>
<calendar>
<id>44</id>
<name>Air Force</name>
<expiry_date>2012-03-01</expiry_date>
<thumbnail_url>http://www.countdownyourgame.com/uploads/44_thumbnail.png</thumbnail_url>
</calendar>
<calendar>
<id>103</id>
<name>Akron</name>
<expiry_date>2012-02-01</expiry_date>
<thumbnail_url>http://www.countdownyourgame.com/uploads/103_thumbnail.png</thumbnail_url>
</calendar>
<calendar>
<id>16</id>
<name>Alabama</name>
<expiry_date>2012-03-01</expiry_date>
<thumbnail_url>http://www.countdownyourgame.com/uploads/16_thumbnail.png</thumbnail_url>
</calendar>
</calendars>
and same response in JSon format
{
"hash":
{
"resp_status":"1",
"message":"success",
"errors":"",
"calendars":
{
"calendar":[
{
"id":"44",
"name":"Air Force",
"expiry_date":"2012-03-01",
"thumbnail_url":"http://www.countdownyourgame.com/uploads/44_thumbnail.png"
},
{
"id":"103",
"name":"Akron",
"expiry_date":"2012-02-01",
"thumbnail_url":"http://www.countdownyourgame.com/uploads/103_thumbnail.png"
},
{
"id":"16",
"name":"Alabama",
"expiry_date":"2012-03-01",
"thumbnail_url":"http://www.countdownyourgame.com/uploads/16_thumbnail.png"
}
]
}
}
}
here is POJO for calendar objects contained inside calendars (file name Calendar.java)
public class Calendar {
private String id, name, expiry_date, thumbnail_url;
Calendar() {
id = new String("");
name = new String("");
expiry_date = new String("");
thumbnail_url = new String("");
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExpiryDate() {
return expiry_date;
}
public void setExpiryDate(String expiry_date) {
this.expiry_date = expiry_date;
}
public String getThumbnailUrl() {
return thumbnail_url;
}
public void setThumbnailUrl(String name) {
this.thumbnail_url = name;
}
}
to convert the above JSon response i just need following code
JSONObject json=new JSONObject(JsonResponceString);
for(int i=0;i<json.getJSONObject("hash").getJSONObject("calendars").getJSONArray("calendar").length();i++)
{
//by using refrenced jar of Gson
Calendars obj=new Gson().fromJson(json.getJSONObject("hash").getJSONObject("calendars").getJSONArray("calendar").getJSONObject(i).toString(), Calendar.class);
//ArrayList for calendar type objects
calendarList.add(obj);
}
for above process with XML there are many parsers but i found XStream the simple one. here as shown in the following link http://x-stream.github.io/tutorial.html in the example there is one object not array of objects which is converted to POJO as defined in bottom portion of code
here is my question that how can i traverse throw whole XML response and get the specific or all calendar objects(XML objects) which can be converted to string like in JSon and then passed as an argument to fromXML() method so that parsed to POJO.
any idea of writing a class by my self to split calendar objects using string methods or regular expression will take the same amount of time as required to choose simple parsing so please help me by giving a clean answer that the process I'm trying is possible or not , possible but not this way...then in what way?
i also studied about others specially JAXB but it needs schema and although it can even design POJOs for you but what if i don't need the whole XML to be parsed the problem with most of parsers i have is they are likely to parse the whole response and hence demanding a messy structure of POJO for this. if I'm wrong then please suggest me but with some solid example...thankx
回答1:
Alternatively you can use SAX parser for parsing xml.
Refer this example code
回答2:
At last found the way resembling to JSon . i hope this can help someone else. @parag this is what i was asking.........i appreciate your help but that was not what i was looking for..
package com.samjanz.xmlparsing;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.samjanz.xmlparsing.helpers.MyConverter;
import com.samjanz.xmlparsing.helpers.MyHTTPConnector;
import com.samjanz.xmlparsing.pojos.Calendar;
import com.thoughtworks.xstream.XStream;
public class XmlParsingActivity extends Activity {
LinearLayout parent;
String serverResponce;
Document xmlDoc;
ArrayList<Calendar> calendarList;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
parent = (LinearLayout) findViewById(R.id.parent);
XStream xstream = new XStream();
xstream.alias("calendar", Calendar.class);
calendarList = new ArrayList<Calendar>();
String url = getText(R.string.calendar_url).toString();
// get DOC
xmlDoc = MyConverter.streamToDocument(MyHTTPConnector.UrlToStream(url));
NodeList nodeLst = xmlDoc.getElementsByTagName("calendar");
for (int i = 0; i < nodeLst.getLength(); i++) {
Node node = nodeLst.item(i);
if (node != null) {
Calendar obj = (Calendar) xstream.fromXML(MyConverter
.nodeToString(node));
calendarList.add(obj);
LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv = new TextView(this);
tv.setLayoutParams(lparams);
tv.setText("\n\nLoop No:" + (i + 1) + "\nId = "
+ calendarList.get(i).getId() + "\nName = "
+ calendarList.get(i).getName() + "\nExpiry Date = "
+ calendarList.get(i).getExpiryDate()
+ "\nThumbnail Url = "
+ calendarList.get(i).getThumbnailUrl());
parent.addView(tv);
}
}
}
}
来源:https://stackoverflow.com/questions/8385470/getting-specific-object-of-xml-which-can-be-parsed-using-xstream