<?xml version="1.0" encoding="UTF-8"?> <persons> <person id=“18"> <name>allen</name> <age>36</age> </person> <person id=“28"> <name>james</name> <age>25</age> </person> </persons>
例子定义了一个javabean用于存放上面解析出来的xml内容, 这个javabean为Person:
public class Person {
private Integer id;
private String name;
private Short age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Short getAge() {
return age;
}
public void setAge(Short age) {
this.age = age;
}
}
import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import cn.itcast.xml.domain.Person; /** * 使用Dom解析xml文件 * */ public class DomXMLReader { public static List<Person> readXML(InputStream inStream) { List<Person> persons = new ArrayList<Person>(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse(inStream); Element root = dom.getDocumentElement(); NodeList items = root.getElementsByTagName("person");//查找所有person节点 for (int i = 0; i < items.getLength(); i++) { Person person = new Person(); //得到第一个person节点 Element personNode = (Element) items.item(i); //获取person节点的id属性值 person.setId(new Integer(personNode.getAttribute("id"))); //获取person节点下的所有子节点(标签之间的空白节点和name/age元素) NodeList childsNodes = personNode.getChildNodes(); for (int j = 0; j < childsNodes.getLength(); j++) { Node node = (Node) childsNodes.item(j); //判断是否为元素类型 if(node.getNodeType() == Node.ELEMENT_NODE){ Element childNode = (Element) node; //判断是否name元素 if ("name".equals(childNode.getNodeName())) { //获取name元素下Text节点,然后从Text节点获取数据 person.setName(childNode.getFirstChild().getNodeValue()); } else if (“age”.equals(childNode.getNodeName())) { person.setAge(new Short(childNode.getFirstChild().getNodeValue())); } } } persons.add(person); } inStream.close(); } catch (Exception e) { e.printStackTrace(); } return persons; }
package com.example.xml;
import java.util.List;
import com.example.domain.Person;
import com.example.service.PersonService;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) this.findViewById(R.id.tv);
PersonService ps =new PersonService(this);
List<Person> persons = ps.getPersons("person.xml");
StringBuffer sb = new StringBuffer();
for(Person person:persons){
String age = "age" + person.getAge();
String name = "name" + person.getName();
String id = "id" + person.getId();
sb.append(name+" "+age+" "+id);
}
tv.setText(sb.toString());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
PersonService.java:package com.example.service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;
import com.example.domain.Person;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.util.Xml;
import android.widget.Toast;
public class PersonService {
private Context context;
public PersonService(Context context) {
this.context = context;
}
/**
* 把person.xml的输入流 解析 转化成list集合
*
* @param filename
* assets目录下的文件名
* @return
*/
public List<Person> getPersons(String filename) {
AssetManager manager = context.getAssets();
try {
InputStream is = manager.open(filename);
// 在android下使用pull解析xml文件
// 1.获取pull解析器的实例
XmlPullParser parser = Xml.newPullParser();
// 2.设置解析器的一些参数
parser.setInput(is, "utf-8");
// 获取pull解析器对应的事件类型
int type = parser.getEventType();
Person person = null;
List<Person> persons = new ArrayList<Person>();
while (type != XmlPullParser.END_DOCUMENT) {
if (type == XmlPullParser.START_TAG) {
if ("person".equals(parser.getName())) {
person = new Person();
int id = Integer.parseInt(parser.getAttributeValue(0));
person.setId(id);
} else if ("name".equals(parser.getName())) {
String name = parser.nextText();
person.setName(name);
} else if ("age".equals(parser.getName())) {
int age = Integer.parseInt(parser.nextText());
person.setAge(age);
}
}
if (type == XmlPullParser.END_TAG) {
if ("person".equals(parser.getName())) {
persons.add(person);
person = null;
}
}
type = parser.next();
}
return persons;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "获取person.xml失败", Toast.LENGTH_SHORT)
.show();
return null;
}
}
/**
* 把persons集合里面的内容写到xml文件里面
*
* @param persons
* person的集合
* @return
*/
public boolean savePersonToXml(List<Person> persons) {
try {
XmlSerializer serializer = Xml.newSerializer();
// /sdcard/person.xml
// mount unmount 文件系统的权限
File file = new File(Environment.getExternalStorageDirectory(),
"person.xml");
FileOutputStream fos = new FileOutputStream(file);
serializer.setOutput(fos, "utf-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null, "persons");
for (Person person : persons) {
serializer.startTag(null, "person");
serializer.attribute(null, "id", person.getId() + "");
serializer.startTag(null, "name");
serializer.text(person.getName());
serializer.endTag(null, "name");
serializer.startTag(null, "age");
serializer.text(person.getAge() + "");
serializer.endTag(null, "age");
serializer.endTag(null, "person");
}
serializer.endTag(null, "persons");
serializer.endDocument();
fos.flush();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Person.java:
package com.example.domain;
public class Person {
private int age;
private int id;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0 && age <= 100) {
this.age = age;
} else {
this.age = 0;
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
person.xml文件(在asserts目录下存放):
<?xml version='1.0' encoding='utf-8'?>
<persons>
<person id="18">
<name>allen</name>
<age>16</age>
</person>
<person id="28">
<name>bing</name>
<age>21</age>
</person>
</persons>