In Android, there are generally several ways to operate xml files: SAX operation, Pull operation, DOM operation, etc. Among them, the DOM method may be the most familiar to everyone, and it is also in line with the W3C standard. As an industry-recognized data exchange format, XML is available on various platforms and languages. Widely used and implemented. Its standard type, reliability, safety... There is no doubt about it. On the Android platform, if we want to implement data storage and data exchange, we often use xml data format and xml files.
Tips:The data stored in android generally includes the following types: SharedPreferences (parameterized), XML file, sqllite database, network, ContentProvider (content provider), etc. In Android, there are generally several ways to operate xml files: SAX operation, Pull operation, DOM operation, etc. Among them, the DOM method may be the most familiar to everyone, and it is also in line with W3C standards.
1)In the Java platform, there are excellent open source packages such as DOM4J, which greatly facilitates everyone’s use of the DOM standard. Manipulate XML files. In JavaScript, different browser parsing engines have slightly different parsing and operations on DOM (but this is not the focus of this chapter). The DOM method also has its shortcomings. Usually, the xml file is loaded once and then parsed using DOM's
api. This consumes a lot of memory and has a certain impact on performance. Although the configuration of our Android phones is constantly being upgraded, in terms of memory, it is still unable to compete with traditional PCs. Therefore, on Android, it is not recommended to use DOM to parse and operate XML.
The code is as follows:package cn.itcast.service;
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.model.Person;
public class DomPersonService {
public List<Person> getPersons(InputStream stream) throws Throwable
{
List<Person> list =new ArrayList<Person>();
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder =factory.newDocumentBuilder();
Document dom = builder.parse(stream);//解析完成,并以dom树的方式存放在内存中。比较消耗性能
//开始使用dom的api去解析
Element root = dom.getDocumentElement();//根元素
NodeList personNodes = root.getElementsByTagName("person");//返回所有的person元素节点
//开始遍历啦
for(int i=0;i<personNodes.getLength();i++)
{
Person person =new Person();
Element personElement =(Element)personNodes.item(i);
person.setId(new Integer( personElement.getAttribute("id")));//将person元素节点的属性节点id的值,赋给person对象
NodeList personChildrenNodes =personElement.getChildNodes();//获取person节点的所有子节点
//遍历所有子节点
for(int j=0;j<personChildrenNodes.getLength();j++)
{
//判断子节点是否是元素节点(如果是文本节点,可能是空白文本,不处理)
if(personChildrenNodes.item(j).getNodeType()==Node.ELEMENT_NODE)
{
//子节点--元素节点
Element childNode =(Element)personChildrenNodes.item(j);
if("name".equals(childNode.getNodeName()))
{
//如果子节点的名称是“name”.将子元素节点的第一个子节点的值赋给person对象
person.setName(childNode.getFirstChild().getNodeValue());
}else if("age".equals(childNode.getNodeValue()))
{
person.setAge(new Integer(childNode.getFirstChild().getNodeValue()));
}
}
}
list.add(person);
}
return list;
}}
##2)
SAX (Simple API for XML) is a very widely used XML parsing standard. Handler mode is usually used to process XML documents. This processing mode is very different from the way we are usually used to understanding it. There are often some friends around who are new to it. When using SAX, you may find it a little difficult to understand. In fact, SAX is not complicated, it is just a different way of thinking. As its name indicates, in order to allow us to process XML documents in a simpler way, let's get started.
Copy code
package cn.itcast.service; import java.io.InputStream;import java.util.ArrayList;import java.util.List; import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler; import cn.itcast.model.Person; public class SAXPersonService { public List<Person> getPersons(InputStream inStream) throws Throwable { SAXParserFactory factory = SAXParserFactory.newInstance();//工厂模式还是单例模式? SAXParser parser =factory.newSAXParser(); PersonParse personParser =new PersonParse(); parser.parse(inStream, personParser); inStream.close(); return personParser.getPerson(); } private final class PersonParse extends DefaultHandler { private List<Person> list = null; Person person =null; private String tag=null; public List<Person> getPerson() { return list; } @Override public void startDocument() throws SAXException { list =new ArrayList<Person>(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if("person".equals(localName)) { //xml元素节点开始时触发,是“person” person = new Person(); person.setId(new Integer(attributes.getValue(0))); } tag =localName;//保存元素节点名称 } @Override public void endElement(String uri, String localName, String qName) throws SAXException { //元素节点结束时触发,是“person” if("person".equals(localName)) { list.add(person); person=null; } tag =null;//结束时,需要清空tag } @Override public void characters(char[] ch, int start, int length) throws SAXException { if(tag!=null) { String data = new String(ch,start,length); if("name".equals(tag)) { person.setName(data); }else if("age".equals(tag)) { person.setAge(new Integer(data)); } } } } }
Pull parsing is very similar to Sax parsing. They are both lightweight parsing. Pull has been embedded in the Android kernel, so we do not need to add a third-party jar package to support Pull. The differences between Pull parsing and Sax parsing are (1) pull triggers the corresponding event after reading the xml file The calling method returns a number (2) pull can control where it wants to parse in the program Stop parsing.
Copy code
The code is as follows:
package cn.itcast.service; import java.io.InputStream;import java.io.Writer;import java.util.ArrayList;import java.util.List; import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlSerializer; import android.util.Xml; import cn.itcast.model.Person; public class PullPersonService { //保存xml文件 public static void saveXML(List<Person> list,Writer write)throws Throwable { XmlSerializer serializer =Xml.newSerializer();//序列化 serializer.setOutput(write);//输出流 serializer.startDocument("UTF-8", true);//开始文档 serializer.startTag(null, "persons"); //循环去添加person for (Person person : list) { serializer.startTag(null, "person"); serializer.attribute(null, "id", person.getId().toString());//设置id属性及属性值 serializer.startTag(null, "name"); serializer.text(person.getName());//文本节点的文本值--name serializer.endTag(null, "name"); serializer.startTag(null, "age"); serializer.text(person.getAge().toString());//文本节点的文本值--age serializer.endTag(null, "age"); serializer.endTag(null, "person"); } serializer.endTag(null, "persons"); serializer.endDocument(); write.flush(); write.close(); } public List<Person> getPersons(InputStream stream) throws Throwable { List<Person> list =null; Person person =null; XmlPullParser parser =Xml.newPullParser(); parser.setInput(stream,"UTF-8"); int type =parser.getEventType();//产生第一个事件 //只要当前事件类型不是”结束文档“,就去循环 while(type!=XmlPullParser.END_DOCUMENT) { switch (type) { case XmlPullParser.START_DOCUMENT: list = new ArrayList<Person>(); break; case XmlPullParser.START_TAG: String name=parser.getName();//获取解析器当前指向的元素名称 if("person".equals(name)) { person =new Person(); person.setId(new Integer(parser.getAttributeValue(0))); } if(person!=null) { if("name".equals(name)) { person.setName(parser.nextText());//获取解析器当前指向的元素的下一个文本节点的文本值 } if("age".equals(name)) { person.setAge(new Integer(parser.nextText())); } } break; case XmlPullParser.END_TAG: if("person".equals(parser.getName())) { list.add(person); person=null; } break; } type=parser.next();//这句千万别忘了哦 } return list; } }
The following is the code of the Person class of the Model layer:
Copy code
The code is as follows:
package cn.itcast.model; public class Person {private Integer id;public Integer getId() { return id;}public void setId(Integer id) { this.id = id;} private String name;public String getName() { return name;} public void setName(String name) { this.name = name;} private Integer age;public Integer getAge() { return age;} public void setAge(Integer age) { this.age = age;} public Person(){}public Person(Integer id, String name, Integer age) { this.id = id; this.name = name; this.age = age;} @Overridepublic String toString() { return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";} }
The above is the detailed content of Summary of three methods of operating XML in Android. For more information, please follow other related articles on the PHP Chinese website!