一.xml数据格式
二、生成XML文件
2.1 Person类
public class Person { private int id; private int age; private String name; private String sex; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Person{" + "id=" + id + ", age=" + age + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; }}
2.2 生成XML文件
public static void createXml(Context context,Listlist) { XmlSerializer serializer=Xml.newSerializer();//xml文件生成器 File file=new File(Environment.getExternalStorageDirectory(),"person.xml"); FileOutputStream fos=null; try { fos=new FileOutputStream(file); serializer.setOutput(fos,"utf-8");//为xml生成器设置输出流和字符编码 serializer.startDocument("utf-8",true);//开始文档,参数分别为字符编码和是否保持独立 serializer.startTag(null,"persons");//开始标签,参数分别为:命名空间和标签名 for(Person person:list){ 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,"sex"); serializer.text(person.getSex()); serializer.endTag(null,"sex"); serializer.startTag(null,"age"); serializer.text(person.getAge()+""); serializer.endTag(null,"age"); serializer.startTag(null,"address"); serializer.text(person.getAddress()); serializer.endTag(null,"address"); serializer.endTag(null,"person"); } serializer.endTag(null,"persons");//结束标签 serializer.endDocument();//结束xml文档 Toast.makeText(context.getApplicationContext(),"生成成功!",Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(context.getApplicationContext(),"生成失败!",Toast.LENGTH_SHORT).show(); e.printStackTrace(); }finally { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
三、XML文件解析
3.1 pull方式
//pull方式解析XML文件 public static ListparseXMLWithPull(File xmlData){ try { FileInputStream fis=new FileInputStream(xmlData); List list=null; Person person=null; //获取xml pull解析器 XmlPullParserFactory factory=XmlPullParserFactory.newInstance(); XmlPullParser xmlPullParser=factory.newPullParser(); xmlPullParser.setInput(fis,"utf-8");//参数分别为输入流和字符编码 int eventType=xmlPullParser.getEventType(); while(eventType!=XmlPullParser.END_DOCUMENT){ //如果事件不等于文档结束事件就继续循环 switch (eventType){ case XmlPullParser.START_TAG: if("persons".equals(xmlPullParser.getName())){ list=new ArrayList<>(); }else if("person".equals(xmlPullParser.getName())){ person=new Person(); person.setId(Integer.valueOf(xmlPullParser.getAttributeValue(0))); }else if("name".equals(xmlPullParser.getName())){ person.setName(xmlPullParser.nextText()); }else if("sex".equals(xmlPullParser.getName())){ person.setSex(xmlPullParser.nextText()); }else if("address".equals(xmlPullParser.getName())){ person.setAddress(xmlPullParser.nextText()); }else if("age".equals(xmlPullParser.getName())){ person.setAge(Integer.valueOf(xmlPullParser.nextText())); } break; case XmlPullParser.END_TAG: if("person".equals(xmlPullParser.getName())){ list.add(person); person=null; } break; } eventType=xmlPullParser.next(); } return list; } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (XmlPullParserException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } }
3.2 sax方式解析
//SAX方式解析XML文件 public static ListparseXMLWithSAX(File xmlData){ try { SAXParserFactory factory=SAXParserFactory.newInstance();//创建SAX解析工厂 SAXParser saxParser=factory.newSAXParser();//创建SAX解析器 SAXHandler handler=new SAXHandler();//创建处理函数 saxParser.parse(xmlData,handler);//开始解析 List list= handler.getPersons();//获取返回数据 return list; } catch (ParserConfigurationException e) { e.printStackTrace(); return null; } catch (SAXException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } } //SAX处理类 private static class SAXHandler extends DefaultHandler{ private List list=null; private Person person=null; private String nodeName="";//当前解析的标签 //返回解析结果 public List getPersons(){ return list; } //文档开始 @Override public void startDocument() throws SAXException { super.startDocument(); list=new ArrayList<>(); } //文档结束 @Override public void endDocument() throws SAXException { super.endDocument(); } //节点开始标签 @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); nodeName=localName; if("person".equals(localName)){ person=new Person(); person.setId(Integer.valueOf(attributes.getValue("id"))); } } //节点结束标签 @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); if("person".equals(localName)){ list.add(person); person=null; } nodeName=""; } //文本数据 如果标签存在换行也会进入该方法,但是data数据为null,记得做非空判断" @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); String data=new String(ch,start,length); if(!TextUtils.isEmpty(data)&&!TextUtils.isEmpty(nodeName)){ return; } if("age".equals(nodeName)){ person.setAge(Integer.valueOf(data)); }else if("address".equals(nodeName)){ person.setAddress(data); }else if("name".equals(nodeName)){ person.setName(data); }else if("sex".equals(nodeName)){ person.setSex(data); } } }
3.3 Dom解析XML文件
//DOM解析XML文件 private ListparseXMLWithDom(File xmlData){ List list=new ArrayList<>(); try { //获得工厂对象,以及通过DOM工厂对象获取DOMBuilder对象 DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); //解析XML输入流,得到Document对象,表示一个XML文档 InputStream fis=getAssets().open("person.xml"); Document document=builder.parse(xmlData); //获取文档中的根节点persons Element element=document.getDocumentElement(); //获取Element下一级的person节点集合,以及NodeList的形式存放 NodeList peronsNodes=element.getElementsByTagName("person"); for(int i=0;i