Method for parsing XML files in the Android system

  • 2020-04-01 04:04:31
  • OfStack

preface
      When learning the source code of the Framework layer of Android, Android USES XmlPullParser extensively to parse the source code of XML files. So, by the way, here's a look at the use of XmlPullParser.

XML
      The Chinese name of XML (eXtensible Markup Language) is eXtensible Markup Language. A mark is a symbol of information that a computer can understand, by which computers can process articles containing various kinds of information.
use
      XML is designed to transmit and carry data information, not to represent or display data, whereas HTML USES presentation data, so the focus of XML usage is that it explains what data is and carries data information.

      Rich documentation - customize the documentation to describe and enrich it       Metadata - describes other files or network information       Configuration document - describes the parameters set by the software

structure
      Each XML document starts with an XML preface, and the first line in the previous code is the XML preface. The & # 63; The XML version = "1.0" & # 63; > . This line of code tells the parser or browser that the file should be parsed according to XML rules. However, the name of the root element is defined by the document type definition or XML schema.

XmlPullParser
      PULL parsing XML is an event-driven way to parse an XML file. When PULL parsing begins, we can first get the current parse event type through the getEventType() method and the next parse event type through the next() method. The PULL parser provides four event resolution types: START_DOCUMENT (start document), END_DOCUMENT (end document), START_TAG (start tag), and END_TAG (end tag). When at an element, you can call the getAttributeValue() method to get the value of the attribute, or you can get the text value of the node through the nextText() method. Here is an example to explain.
XML sample file
      The XML sample file code that needs to be parsed is as follows:


  <?xml version="1.0" encoding="UTF-8"?> 
  <colleagues> 
    <colleague id="1"> 
      <name> A mouse </name> 
      <age>24</age> 
      <sex>boy</sex> 
    </colleague> 
    <colleague id="2"> 
      <name> Life of </name> 
      <age>28</age> 
      <sex>girl</sex> 
    </colleague> 
    <colleague id="3"> 
      <name> Chen Shan </name> 
      <age>26</age> 
      <sex>boy</sex> 
    </colleague> 
  </colleagues> 

XmlPullParser parser


  package com.example.shakedemo; 
   
  import java.io.File; 
  import java.io.FileNotFoundException; 
  import java.io.FileReader; 
  import java.io.IOException; 
  import java.util.ArrayList; 
  import java.util.List; 
  import org.xmlpull.v1.XmlPullParser; 
  import org.xmlpull.v1.XmlPullParserException; 
  import org.xmlpull.v1.XmlPullParserFactory; 
  import android.R.xml; 
  import android.util.Log; 
  import android.util.Xml; 
   
  public class XmlPullParserHelper { 
   
    public static List<Colleague> getColleagues(String xmlFilePath) { 
      List<Colleague> colleagues = new ArrayList<Colleague>(); 
      FileReader xmlReader = null; 
      try { 
        xmlReader = new FileReader(new File(xmlFilePath)); 
      } catch (FileNotFoundException e) { 
        Log.e("wzy", "Couldn't find xml file " + xmlFilePath); 
        return colleagues; 
      } 
   
      try { 
   
        //Approach 1: get the parser object using the android.util.xml class provided by Android
        XmlPullParser parser = Xml.newPullParser(); 
   
        //Approach 2: use the factory class XmlPullParserFactory
        // XmlPullParserFactory pullFactory = 
        // XmlPullParserFactory.newInstance(); 
        // XmlPullParser parser = pullFactory.newPullParser(); 
   
        //Set the file input stream
        parser.setInput(xmlReader); 
   
        //Gets the current event type
        int eventType = parser.getEventType(); 
   
        Colleague colleague = null; 
   
        while (eventType != XmlPullParser.END_DOCUMENT) { 
          switch (eventType) { 
          case XmlPullParser.START_DOCUMENT: 
            break; 
          case XmlPullParser.START_TAG: 
             
            String name = parser.getName(); 
            if ("colleague".equals(name)) { 
              colleague = new Colleague(); 
              colleague.setId(Integer.parseInt(parser.getAttributeValue(null, "id"))); 
            } else if ("name".equals(name)) { 
              if (colleague != null) { 
                colleague.setName(parser.nextText()); 
              } 
            } else if ("age".equals(name)) { 
              if (colleague != null) { 
                colleague.setAge(Integer.parseInt(parser.nextText())); 
              } 
            } else if ("sex".equals(name)) { 
              if (colleague != null) { 
                colleague.setSex(parser.nextText()); 
              } 
            } 
   
            break; 
          case XmlPullParser.END_TAG: 
            if ("colleague".equals(parser.getName()) && colleague != null) { 
              colleagues.add(colleague); 
              colleague = null; 
            } 
            break; 
          } 
   
          eventType = parser.next(); 
        } 
   
        xmlReader.close(); 
      } catch (XmlPullParserException e) { 
        // Do nothing 
      } catch (IOException e) { 
        // Do nothing 
      } 
   
      return colleagues; 
    } 
  } 

      The colleague class is simply defined as follows:

   


 package com.example.shakedemo; 
   
  public class Colleague { 
    private int id; 
    private int age; 
    private String name; 
    private String sex; 
   
    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; 
    } 
   
    @Override 
    public String toString() { 
      return "ID is " + id + ", Name is " + name + ", Sex is " + sex; 
    } 
   
  } 


Related articles: