As an industry-recognized data exchange format, XML is widely used and implemented on various platforms and languages. Its standard type, reliability, safety...no doubt. On the Android platform, if we want to realize data storage and data exchange, we often use xml data format and xml files.
Tips:There are generally the following types of data stored in Android: SharedPreferences (parameterization), XML files, SQLite databases, networks, ContentProvider (content providers), etc.
In android, there are generally several ways to operate XML files: SAX operations, Pull operations, DOM operations, etc. Among them, the DOM method is probably the most familiar to everyone and also meets the W3C standard.
1)
In the Java platform, there are excellent open source packages such as DOM4J, which are very convenient for everyone to use the DOM standard to operate XML files. In JavaScript, different browser parsing engines also have slight differences in the parsing and operation of DOM (but this is not the focus of this chapter). The DOM method also has its shortcomings. Usually, the XML file is loaded at one time and then the DOM API is used for parsing, which consumes memory to a large extent and has a certain impact on performance. Although our Android phones are constantly upgrading their configuration, their memory is not comparable to traditional PCs for the time being. Therefore, on Android, it is not recommended to use DOM to parse and manipulate XML.
package ;
import ;
import ;
import ;
import ;
import ;
import org.;
import org.;
import org.;
import org.;
import ;
public class DomPersonService {
public List<Person> getPersons(InputStream stream) throws Throwable
{
List<Person> list =new ArrayList<Person>();
DocumentBuilderFactory factory =();
DocumentBuilder builder =();
Document dom = (stream);//The parsing is completed and stored in memory in the form of a dom tree. Comparative performance consumption
//Start use the dom API to parse
Element root = ();//root element
NodeList personNodes = ("person");//Return all person element nodes
//The traversal begins
for(int i=0;i<();i++)
{
Person person =new Person();
Element personElement =(Element)(i);
(new Integer( ("id")));// Assign the value of the attribute node id of the person element node to the person object
NodeList personChildrenNodes =();//Get all child nodes of person node
//Transfer all child nodes
for(int j=0;j<();j++)
{
//Determine whether the child node is an element node (if it is a text node, it may be blank text, and will not be processed)
if((j).getNodeType()==Node.ELEMENT_NODE)
{
//Sub-Element node
Element childNode =(Element)(j);
if("name".equals(()))
{
//If the name of the child node is "name", assign the value of the first child node of the child element node to the person object
(().getNodeValue());
}else if("age".equals(()))
{
(new Integer(().getNodeValue()));
}
}
}
(person);
}
return list;
}
}
2)
SAX (Simple API for XML) is a very widely used XML parsing standard. It usually uses the Handler pattern to process XML documents. This processing pattern is very different from the way we understand it normally. There are often some friends around you who find it difficult to understand when they first come into contact with SAX. In fact, SAX is not complicated, it just changes its way of thinking. As its name indicates, in order to allow us to process XML documents in a simpler way, let's start.
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class SAXPersonService {
public List<Person> getPersons(InputStream inStream) throws Throwable
{
SAXParserFactory factory = ();//Factory mode or singleton mode?
SAXParser parser =();
PersonParse personParser =new PersonParse();
(inStream, personParser);
();
return ();
}
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))
{
//The xml element node is triggered at the beginning, and it is "person"
person = new Person();
(new Integer((0)));
}
tag =localName;//Save element node name
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
//Flashes when the element node ends, it is "person"
if("person".equals(localName))
{
(person);
person=null;
}
tag = null;// At the end, you need to clear the 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))
{
(data);
}else if("age".equals(tag))
{
(new Integer(data));
}
}
}
}
}
3)
Pull parsing and Sax parsing are very similar. They are both lightweight parsing. Pull is already embedded in the Android kernel, so we don't need to add third-party jar packages to support Pull. The difference between Pull parsing and Sax parsing is (1) Pull reads the xml file and triggers the corresponding event call method. The return is the number (2). Pull can control where you want to parse it in the program and stop parsing it.
package ;
import ;
import ;
import ;
import ;
import .;
import .;
import ;
import ;
public class PullPersonService {
//Save the xml file
public static void saveXML(List<Person> list,Writer write)throws Throwable
{
XmlSerializer serializer =();//Serialization
(write);//Output stream
("UTF-8", true);//Start the document
(null, "persons");
//Loop to add person
for (Person person : list) {
(null, "person");
(null, "id", ().toString());//Set the id attribute and attribute value
(null, "name");
(());//The text value of the text node--name
(null, "name");
(null, "age");
(().toString());//The text value of the text node--age
(null, "age");
(null, "person");
}
(null, "persons");
();
();
();
}
public List<Person> getPersons(InputStream stream) throws Throwable
{
List<Person> list =null;
Person person =null;
XmlPullParser parser =();
(stream,"UTF-8");
int type =();//generates the first event
//As long as the current event type is not "end document", go to loop
while(type!=XmlPullParser.END_DOCUMENT)
{
switch (type) {
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<Person>();
break;
case XmlPullParser.START_TAG:
String name=();//Get the element name currently pointed to by the parser
if("person".equals(name))
{
person =new Person();
(new Integer((0)));
}
if(person!=null)
{
if("name".equals(name))
{
(());//Get the text value of the next text node of the element currently pointed to by the parser
}
if("age".equals(name))
{
(new Integer(()));
}
}
break;
case XmlPullParser.END_TAG:
if("person".equals(()))
{
(person);
person=null;
}
break;
}
type=();//Don't forget this sentence
}
return list;
}
}
Here is the code of the Person class of the Model layer:
package ;
public class Person {
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
= id;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
= name;
}
private Integer age;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
= age;
}
public Person()
{
}
public Person(Integer id, String name, Integer age) {
= id;
= name;
= age;
}
@Override
public String toString() {
return "Person [, name=" + name + ", age=" + age + "]";
}
}