不用说,这个简单,只需要知道几个类就行了,具体类如下:
1、DocumentBuilderFactory
2、DocumentBuilder
3、Document
4、Element
5、NodeList
具体代码如下:
1、XML文件见上Android网络编程一
2、实体类如上
3、服务类:
public class PersonDOMService {
public static ArrayList<Person> getPersons(String uri) throws Exception
{
File file=new File(uri);
InputStream inStream=new FileInputStream(file);
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(inStream);
Element root=document.getDocumentElement();//获取文档的根
NodeList personNodes=root.getElementsByTagName("person");
ArrayList<Person> persons=new ArrayList<Person>();
Person person;
Element perElement;
for(int i=0;i<personNodes.getLength();i++)
{
perElement=(Element)personNodes.item(i);
int id=new Integer(perElement.getAttribute("id"));
person=new Person();
person.setId(id);
NodeList childNodes=perElement.getChildNodes();//读取person下的节点
for(int j=0;j<childNodes.getLength();j++)
{
if(childNodes.item(j).getNodeType()==Node.ELEMENT_NODE)
{
if("name".equals(childNodes.item(j).getNodeName()))
{
person.setName(childNodes.item(j).getFirstChild().getNodeValue());
}
else if("sex".equals(childNodes.item(j).getNodeName()))
{
person.setSex(childNodes.item(j).getFirstChild().getNodeValue());
}
else
person.setAge(new Short(childNodes.item(j).getFirstChild().getNodeValue()));
}
}
persons.add(person);
}
inStream.close();
return persons;
}
}
4、PC端调用代码如下:
public class TestPerson {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
String uri="D:\\JavaEETemp\\testsaxdemo\\src\\testsaxdemo\\demo\\persons.xml";
ArrayList<Person> persons=PersonDOMService.getPersons(uri);
Person person;
for(int i=0;i<persons.size();i++)
{
person=persons.get(i);
System.out.println("id="+person.getId()+",name="+person.getName()+",sex="+person.getSex()+",age="+person.getAge());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}