Summary of several methods for android operation XML

  • 2020-05-17 06:30:59
  • OfStack

As an industry-recognized data exchange format, XML is widely used and implemented on various platforms and languages. Its standard, reliability, safety... No doubt about it. On the android platform, we often use the xml data format and xml files to achieve data storage and data exchange.

Tip: there are several types of data 1 stored in android: SharedPreferences(parameterization), XML files, sqllite databases, network, ContentProvider (content provider), and so on.

In android, there are several ways to operate xml file, 1: SAX operation, Pull operation, DOM operation and so on. Among them, DOM is probably the most familiar one, and it also conforms to the standard of W3C.

1)

In the java platform, there are excellent open source packages such as DOM4J, which make it extremely easy for people to use the DOM standard to manipulate XML files. In javascript, the parsing and operation of DOM vary slightly between different browser parsing engines (though that's not the point of this chapter). The DOM approach, however, has its drawbacks. Usually, the xml file is loaded once and then parsed using api of DOM, which consumes memory to a large extent and has a definite impact on performance. While our android phones are constantly upgrading their configuration, they still cannot match the traditional PC in terms of memory. Therefore, on android, it is not recommended to use DOM to parse and manipulate XML.


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);// Parsing is done and done dom The tree is stored in memory. Comparative consumption performance 
   // Begin to use dom the api To resolve 
   Element root = dom.getDocumentElement();// The root element 
  NodeList personNodes = root.getElementsByTagName("person");// Return all person Element nodes 
  // Let's go through it 
  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")));// will person Attribute nodes of element nodes id The value of. Assign to person object 
    NodeList personChildrenNodes =personElement.getChildNodes();// To obtain person All child nodes of a node 
    // Traverse all child nodes 
    for(int j=0;j<personChildrenNodes.getLength();j++)
    {
     // Determine whether the child node is an element node (if it is a text node, it may be blank text, not processed) 
     if(personChildrenNodes.item(j).getNodeType()==Node.ELEMENT_NODE)
     {
      // Child nodes -- Element nodes 
      Element childNode =(Element)personChildrenNodes.item(j);
         if("name".equals(childNode.getNodeName()))
         {
          // If the name of the child node is" name " . Will be the child of the node 1 The value of the child node is assigned to person object 
          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 widely used XML parsing standard. Handler mode is usually used to process XML documents. This mode is quite different from the way we are used to understand SAX. SAX is not complicated, just a different way of thinking. As the name suggests, let's get started in order to deal with XML documents in a simpler way.


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();// Factory mode or singleton mode? 
    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 Triggered at the beginning of the element node, which is" person " 
   person = new Person();
   person.setId(new Integer(attributes.getValue(0)));
  }
  tag =localName;// Save the element node name 
 }
 @Override
 public void endElement(String uri, String localName, String qName)
   throws SAXException {
  // Triggered at the end of the element node, which is" person " 
  if("person".equals(localName))
  {
   list.add(person);
   person=null;
  }
  tag =null;// When you're done, you need to clear 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));
     }
     }
 }

   }
}

3)

Pull parsing is similar to Sax parsing, both of which are lightweight parsing. Pull is already embedded in the kernel of Android, so we don't need to add the 3rd jar package to support Pull. The difference between Pull parsing and Sax parsing is that (1)pull reads the xml file, triggers the corresponding event and calls the method to return the number (2)pull can control in the program where it wants to parse to stop parsing.


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 {
 // save xml file 
 public static void saveXML(List<Person> list,Writer write)throws Throwable
 {
  XmlSerializer serializer =Xml.newSerializer();// serialization 
  serializer.setOutput(write);// The output stream 
  serializer.startDocument("UTF-8", true);// Began to document 
  serializer.startTag(null, "persons");
  // Loop to add person
  for (Person person : list) {
   serializer.startTag(null, "person");
   serializer.attribute(null, "id", person.getId().toString());// Set up the id Properties and their values 
   serializer.startTag(null, "name");
   serializer.text(person.getName());// The text value of the text node --name
   serializer.endTag(null, "name");
   serializer.startTag(null, "age");
   serializer.text(person.getAge().toString());// The text value of the text node --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();// To produce the first 1 An event 
     // Loop as long as the current event type is not "end document" 
     while(type!=XmlPullParser.END_DOCUMENT)
     {
     switch (type) {
  case XmlPullParser.START_DOCUMENT:
  list = new ArrayList<Person>();
   break;
  case XmlPullParser.START_TAG:
   String name=parser.getName();// Gets the name of the element currently pointed to by the parser 
   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());// Gets the bottom of the element that the parser is currently pointing to 1 The text value of a text node 
    }
    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();// Don't forget that 
     }
   return list;
  }
}

Below is the code for the Person class in the Model layer:

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;
}

@Override
public String toString() {
 return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}


Related articles: