xml解析與xml的生成

<?xml version="1.0" encoding="UTF-8"?><persons>  
 <person id="1">      
 <name>張三</name>       
<age>18</age>   
</person>   
<person id="2">    
   <name>李四</name>    
   <age>14</age>   
</person>
</persons>



 

1、首先是準備xml文件

2、進行解析


public class XmlService {

 /**
  * 獲取Person
  * document 解析:把整個文檔樹讀入到內存中,內存消耗大
  * sax解析  :基於事件,一個一個的解析
  * 
  * android有自己的xml解析機制:Pull解析  --》和sax解析很像,也是基於事件的
  * 
  * 
  * 
  * @return
  * @throws Exception 
  */
 public List<PersonInfo> getPersons(InputStream inputStream, String inputEncoding) throws Exception{
  
  List<PersonInfo> infos = null;
  PersonInfo info = null;
  
  //解析工廠
  XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
  //通過解析工廠解析器
  XmlPullParser parser = factory.newPullParser();
  //設置解析數據
  parser.setInput(inputStream, inputEncoding);
  //獲取解析事件類型
  int eventType = parser.getEventType();
  //只要沒有解析到文檔的結尾就繼續解析
  while(eventType != XmlPullParser.END_DOCUMENT){
   switch (eventType) {
   //parser.getName() 獲取節點的名字
   case XmlPullParser.START_TAG:
    if("persons".equals(parser.getName())){
     infos = new ArrayList<PersonInfo>();
    }else if("person".equals(parser.getName())){
     info = new PersonInfo();
     //parser.getAttributeValue(0) 獲取節點的屬性
     int id = Integer.parseInt(parser.getAttributeValue(0));
     info.id = id;
    }else if("name".equals(parser.getName())){
     //parser.nextText() 下個文本節點的值
     String name = parser.nextText();
     info.name = name;
    }else if("age".equals(parser.getName())){
     int age = Integer.parseInt(parser.nextText());
     info.age = age;
    }
    break;
   case XmlPullParser.END_TAG:
    if("person".equals(parser.getName())){
     infos.add(info);
     info = null;
    }
    break;

   default:
    break;
   }
   
   //繼續解析
   eventType = parser.next();
  }
  
  return infos;
 }


 

 

 

 

xml文件的生成
 

/**
  * 把對象集合以xml的形式保存
  * @param infos
  * @throws Exception 
  */
 public void createXml(List<PersonInfo> infos,OutputStream os) throws Exception{
  /*XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
  //序列化器
  XmlSerializer serializer = factory.newSerializer();*/
  
  XmlSerializer serializer = Xml.newSerializer();  //xml封裝好的序列化器對象方法,相當於上面兩行代碼
  //指定輸出流
  serializer.setOutput(os, "UTF-8");
  
  //文檔開始
  serializer.startDocument("UTF-8", true);
  
  //標籤開始
  serializer.startTag(null, "persons");
  
  for(PersonInfo info:infos){
   serializer.startTag(null, "person");
   
   //屬性
   serializer.attribute(null, "id", info.id+"");

   //name
   serializer.startTag(null, "name");
   serializer.text(info.name);
   serializer.endTag(null, "name");
   
   
   //age
   serializer.startTag(null, "age");
   serializer.text(info.age+"");
   serializer.endTag(null, "age");
   
   serializer.endTag(null, "person");
   
  }
  
  //標籤的結束
  serializer.endTag(null, "persons");
  
  //文檔結束
  serializer.endDocument();
 }
 


 

 


準備數據類接收

</pre><pre class="java" name="code">package com.jky.xml.domain;

public class PersonInfo {

	public int id;
	public String name;
	public int age;
	public PersonInfo() {
		super();
		// TODO Auto-generated constructor stub
	}
	public PersonInfo(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "PersonInfo [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
}


測試類進行測試

public class XmlServiceTest extends AndroidTestCase {

	public void testGetPersons() throws Exception{
		XmlService xs = new XmlService();
		//獲取流,此時模擬的xml文件需要在src文件夾下
                //   InputStream inputStream = getClass().getClassLoader().getResourceAsStream("persons.xml");
		//此時模擬的xml文件可以在當前測試類文件夾下
                  InputStream inputStream = getClass().getResourceAsStream("persons.xml");
		
		List<PersonInfo> persons = xs.getPersons(inputStream, "UTF-8");
		for(PersonInfo info:persons){
			Log.i("i", info.toString());
		}
	}
	
	
	public void testCreateXml() throws Exception{
		XmlService xs = new XmlService();
		List<PersonInfo> infos = new ArrayList<PersonInfo>();
		infos.add(new PersonInfo(1, "james", 18));
		infos.add(new PersonInfo(2, "allen", 21));
		
		OutputStream os = getContext().openFileOutput("persons.xml", Context.MODE_PRIVATE);
		xs.createXml(infos, os);
		
	}
}



 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章