在android下通过xstream解析xml格式信息一文中介绍了通过xstream解析比较简单的xml文件到相应的Java bean中,下面介绍带节点的xml文件,xml文件格式如下
<?xml version="1.0" encoding="utf-8"?>
<city id="1">
<name>
<item lang="en"><value>ShangHai</value></item>
<item lang="zh"><value>上海</value></item>
</name>
<content>
<item lang="en"><value>ShangHai ...</value></item>
<item lang="zh"><value>上海...</value></item>
</content>
<images>
<item name="title" src="http://mp.myvsp.cn/images/shanghai.png"/>
</images>
</city>
解析的代码如下:
1、先创建相应的java bean:
public class CityInfo {
private String id;
private List<ItemInfo> name=new ArrayList<ItemInfo>();
private List<ItemInfo> content=new ArrayList<ItemInfo>();
private List<ItemInfo> images=new ArrayList<ItemInfo>();
相应的set/get方法
public class ItemInfo {
String value;
private String lang;
private String name;
private String src;
相应的set/get方法
2、通过xstream解析xml文件
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.textView=(TextView) this.findViewById(R.id.TextView01);
HttpClient client = new DefaultHttpClient();
StringBuilder builder = new StringBuilder();
HttpGet get = new HttpGet("链接地址");
try {
HttpResponse response = client.execute(get);
BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent()));
for (String s = reader.readLine(); s != null; s = reader.readLine()) {
builder.append(s);
}
Log.v("response","product:"+builder.toString());
XStream xstream = new XStream();
xstream.alias("city", CityInfo.class);
xstream.alias("item", ItemInfo.class);
xstream.useAttributeFor(CityInfo.class,"id");
xstream.useAttributeFor(ItemInfo.class,"lang");
xstream.useAttributeFor(ItemInfo.class,"name");
xstream.useAttributeFor(ItemInfo.class,"src");
CityInfo cityInfo=(CityInfo) xstream.fromXML(builder.toString());
Log.i("response",xstream.toXML(cityInfo));
textView.setText(((ItemInfo)cityInfo.getName().get(1)).getValue());
} catch (Exception e)
{
e.printStackTrace();
}
}
源代码: http://easymorse-android.googlecode.com/svn/trunk/android.readxml/