android下經過xstream解析複雜的xml格式信息

android下經過xstream解析xml格式信息一文中介紹了經過xstream解析比較簡單的xml文件到相應的Java bean中,下面介紹帶節點的xml文件,xml文件格式以下java


<?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>

解析的代碼以下:android

一、先建立相應的java bean:app

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方法

二、經過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/
相關文章
相關標籤/搜索