Five Ways of Data Parsing in Android

  • 2021-11-02 02:27:26
  • OfStack

Here is an XML file. Next, we will parse this file in different parsing methods


<?xml version="1.0" encoding="UTF-8"?>
<Movies>
  <Movie id="1">
    <name> Angry Birds </name>
    <type>Animation</type>
    <year>2016</year>
  </Movie>
  <Movie id="2">
    <name> Ip Man 3</name>
    <type>Action</type>
    <language>English</language>
  </Movie>
</Movies>

1. DOM parsing


//1. Create 1 A DocumentBuilderFactory Object 
    DocumentBuilderFactory dBuilderFactory=DocumentBuilderFactory.newInstance();
    try {
      //2. Create 1 A DocumentBuilder Object 
      DocumentBuilder dBuilder=dBuilderFactory.newDocumentBuilder();
      //3. Get Document Object 
      Document document=dBuilder.parse("Movie.xml");
      System.out.println(" Parsing start :--------------------------");
      // Get Movie Element node set 
      NodeList movies=document.getElementsByTagName("Movie");
      System.out.println(" Shared "+movies.getLength()+" Movie ");
      // Traversal Movie Element node set 
      for(int i=0;i<movies.getLength();i++){
        System.out.println("=====================");
        System.out.println(" Parsing "+(i+1)+" A movie! ");
        Node movie=movies.item(i);
        // Gets the attribute collection of element nodes 
        NamedNodeMap attrs=movie.getAttributes();
        for(int j=0;j<attrs.getLength();j++){
          Node attr=attrs.item(j);
          System.out.print(" The property is named :"+attr.getNodeName()+"    ");
          System.out.println(" Property value is :"+attr.getNodeValue());
        }
        // Get movie Element child node collection 
        NodeList childNodes=movie.getChildNodes();
        for(int k=0;k<childNodes.getLength();k++){
          Node child=childNodes.item(k);
          if (child.getNodeType()==Document.ELEMENT_NODE) {
            System.out.println(" Node name :"+child.getNodeName()+"    ");
            //System.out.println(" Node value :"+child.getNodeValue());
            System.out.println(" Node value :"+child.getFirstChild().getNodeValue());
          }
        }
        System.out.println(" No. 1 "+(i+1)+" The analysis of the film is over ");
      }
      System.out.println(" End of parsing --------------------------------");
    } catch (Exception e) {
      e.printStackTrace();
    }

2. SAX parsing


//1. Create SAXFactory Object 
    SAXParserFactory sParserFactory=SAXParserFactory .newInstance();
    //2. Get 1 A SAXParser Parse object 
    try {
      SAXParser saxParser=sParserFactory.newSAXParser();
      saxParser.parse("Movie.xml",new MyHandler() );
    } catch (Exception e) {
      e.printStackTrace();
    }

Next, you need to write a class to inherit DefaultHandler, and then override the five methods in it:

1) startDocument (), the execution of this method 1 indicates the beginning of parsing, in which the object collection can be initialized


@Override
  public void startDocument() throws SAXException {
    System.out.println(" Start parsing ----------------------------");
    movieList=new ArrayList<>();
  }

2) startEnement (), the execution of this method 1 means that the starting element is parsed, that is, the Movie tag in the xml file


@Override
  public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    //
    if ("Movie".equals(qName)) {
      movie=new Movie();
      count++;
      System.out.println(" Parsing the "+count+" A movie! ");
      for (int i = 0; i < attributes.getLength(); i++) {
        // Get the property name and property value 
        System.out.print(" Attribute name :"+attributes.getQName(i)+"    ");
        System.out.println(" Attribute value :"+attributes.getValue(i));
        if (attributes.getQName(i).equals("id")) {
          movie.setMovieId(attributes.getValue(i));
        }
      }
    }
  }

3) characters (), in which the value of the element is read


@Override
  public void characters(char[] ch, int start, int length) throws SAXException {
    value=new String(ch,start,length);
    if (!value.trim().equals("")) {
      System.out.println(" Node value :"+value);
    }
  }

4) endElement (), which means that the end tag of an element is resolved. In this method, the object can be constructed and finally added to the collection


@Override
  public void endElement(String uri, String localName, String qName) throws SAXException {
    if (qName.equals("year")) {
      movie.setMovieYear(value);
    }
    if (qName.equals("type")) {
      movie.setMovieType(value);
    }
    if (qName.equals("language")) {
      movie.setMovieLanguage(value);
    }
    if (qName.equals("name")) {
      movie.setMovieName(value);
    }
    // Finish parsing 1 Callback when 1 element 
    if ("Movie".equals(qName)) {
      movieList.add(movie);
      movie=null;
      System.out.println(" No. 1 "+count+" The film analysis is over! ");
    }
  }

5) endDocument (), when this method is executed, it means that the file has been parsed


@Override
  public void endDocument() throws SAXException {
    System.out.println(" End of parsing ----------------------------");
    System.out.println(" The parsing result set is as follows :");
    for(int i=0;i<movieList.size();i++){
      System.out.println(movieList.get(i).toString());
      System.out.println("----------------------------------");
    }
  }

3. PULL parsing

pull parsing is different from other methods in that it needs to store the xml file in the xml folder under the resource file res. The parsing process is as follows:

1) First, get an Pull resource parser. Sometimes, if you download an xml file on the network, you need to construct an Pull parser, then set the stream to an pull parser, and then parse one sample, one tag and one tag


// Get 1 A XMLResourceParser
    //XmlPullParser parser=Xml.newPullParser();
    //parser.setInput(in);
    XmlResourceParser xmlResourceParser=getResources().getXml(R.xml.movie);
    // Get the first 1 Event types, that is, the outermost label 
    try {
      int type=xmlResourceParser.getEventType();
      while(type!=XmlResourceParser.END_DOCUMENT){
        if (type==XmlResourceParser.START_DOCUMENT) {
          System.out.println(" Start parsing ");
          movieList=new ArrayList<>();
        }
        if (type==XmlResourceParser.START_TAG) {
          if ("Movie".equals(xmlResourceParser.getName())) {
            movie=new Movie();
            String id=xmlResourceParser.getAttributeValue(null, "id");
            System.out.println("id:"+id);
            movie.setMovieId(id);
          }
          if ("name".equals(xmlResourceParser.getName())) {
            //System.out.println("name:"+xmlResourceParser.nextText()+"===========");
            movie.setMovieName(xmlResourceParser.nextText());
          }else if ("type".equals(xmlResourceParser.getName())) {
            movie.setMovieType(xmlResourceParser.nextText());
          }else if ("year".equals(xmlResourceParser.getName())) {
            movie.setMovieYear(xmlResourceParser.nextText());
          }else if ("language".equals(xmlResourceParser.getName())) {
            movie.setMovieLanguage(xmlResourceParser.nextText());
          }
        }
        if (type==XmlResourceParser.END_TAG) {
          if ("Movie".equals(xmlResourceParser.getName())) {
            movieList.add(movie);
            movie=null;
          }
        }
        type=xmlResourceParser.next();
      }
      System.out.println(" End of parsing ");
      StringBuffer sBuffer=new StringBuffer();
      for (int i = 0; i < movieList.size(); i++) {
        sBuffer.append(movieList.get(i).toString())
        .append("\n");
      }
      show_tv.setText(sBuffer.toString());
    } catch (Exception e) {
      e.printStackTrace();
    }

4. Json parsing

If Json is analyzed, it is necessary to give a copy of JSon data first, so take down the data to analyze it!


private static final String JSONDATA="{name: Zhang 3,"
      + "age:26,"
      + "phone:[131,132],"
      + "score:{"
      + " Language :100,"
      + " Mathematics :90,"
      + " Comprehensive management :{ Chemistry :80, Physics :70, Biology :80}}}";

The process of Json parsing is undoubtedly to encounter curly braces, come out with new1 Object, come out with middle brackets, and then use an for loop to read data:


//1. Create 1 A DocumentBuilderFactory Object 
    DocumentBuilderFactory dBuilderFactory=DocumentBuilderFactory.newInstance();
    try {
      //2. Create 1 A DocumentBuilder Object 
      DocumentBuilder dBuilder=dBuilderFactory.newDocumentBuilder();
      //3. Get Document Object 
      Document document=dBuilder.parse("Movie.xml");
      System.out.println(" Parsing start :--------------------------");
      // Get Movie Element node set 
      NodeList movies=document.getElementsByTagName("Movie");
      System.out.println(" Shared "+movies.getLength()+" Movie ");
      // Traversal Movie Element node set 
      for(int i=0;i<movies.getLength();i++){
        System.out.println("=====================");
        System.out.println(" Parsing "+(i+1)+" A movie! ");
        Node movie=movies.item(i);
        // Gets the attribute collection of element nodes 
        NamedNodeMap attrs=movie.getAttributes();
        for(int j=0;j<attrs.getLength();j++){
          Node attr=attrs.item(j);
          System.out.print(" The property is named :"+attr.getNodeName()+"    ");
          System.out.println(" Property value is :"+attr.getNodeValue());
        }
        // Get movie Element child node collection 
        NodeList childNodes=movie.getChildNodes();
        for(int k=0;k<childNodes.getLength();k++){
          Node child=childNodes.item(k);
          if (child.getNodeType()==Document.ELEMENT_NODE) {
            System.out.println(" Node name :"+child.getNodeName()+"    ");
            //System.out.println(" Node value :"+child.getNodeValue());
            System.out.println(" Node value :"+child.getFirstChild().getNodeValue());
          }
        }
        System.out.println(" No. 1 "+(i+1)+" The analysis of the film is over ");
      }
      System.out.println(" End of parsing --------------------------------");
    } catch (Exception e) {
      e.printStackTrace();
    }
0

5. GSON parsing

GSON parsing is relatively simple, but it also has the limitation of 1. For example, the attribute field of the data class and the key value must correspond to 11


//1. Create 1 A DocumentBuilderFactory Object 
    DocumentBuilderFactory dBuilderFactory=DocumentBuilderFactory.newInstance();
    try {
      //2. Create 1 A DocumentBuilder Object 
      DocumentBuilder dBuilder=dBuilderFactory.newDocumentBuilder();
      //3. Get Document Object 
      Document document=dBuilder.parse("Movie.xml");
      System.out.println(" Parsing start :--------------------------");
      // Get Movie Element node set 
      NodeList movies=document.getElementsByTagName("Movie");
      System.out.println(" Shared "+movies.getLength()+" Movie ");
      // Traversal Movie Element node set 
      for(int i=0;i<movies.getLength();i++){
        System.out.println("=====================");
        System.out.println(" Parsing "+(i+1)+" A movie! ");
        Node movie=movies.item(i);
        // Gets the attribute collection of element nodes 
        NamedNodeMap attrs=movie.getAttributes();
        for(int j=0;j<attrs.getLength();j++){
          Node attr=attrs.item(j);
          System.out.print(" The property is named :"+attr.getNodeName()+"    ");
          System.out.println(" Property value is :"+attr.getNodeValue());
        }
        // Get movie Element child node collection 
        NodeList childNodes=movie.getChildNodes();
        for(int k=0;k<childNodes.getLength();k++){
          Node child=childNodes.item(k);
          if (child.getNodeType()==Document.ELEMENT_NODE) {
            System.out.println(" Node name :"+child.getNodeName()+"    ");
            //System.out.println(" Node value :"+child.getNodeValue());
            System.out.println(" Node value :"+child.getFirstChild().getNodeValue());
          }
        }
        System.out.println(" No. 1 "+(i+1)+" The analysis of the film is over ");
      }
      System.out.println(" End of parsing --------------------------------");
    } catch (Exception e) {
      e.printStackTrace();
    }
1

Properties of the data class:


//1. Create 1 A DocumentBuilderFactory Object 
    DocumentBuilderFactory dBuilderFactory=DocumentBuilderFactory.newInstance();
    try {
      //2. Create 1 A DocumentBuilder Object 
      DocumentBuilder dBuilder=dBuilderFactory.newDocumentBuilder();
      //3. Get Document Object 
      Document document=dBuilder.parse("Movie.xml");
      System.out.println(" Parsing start :--------------------------");
      // Get Movie Element node set 
      NodeList movies=document.getElementsByTagName("Movie");
      System.out.println(" Shared "+movies.getLength()+" Movie ");
      // Traversal Movie Element node set 
      for(int i=0;i<movies.getLength();i++){
        System.out.println("=====================");
        System.out.println(" Parsing "+(i+1)+" A movie! ");
        Node movie=movies.item(i);
        // Gets the attribute collection of element nodes 
        NamedNodeMap attrs=movie.getAttributes();
        for(int j=0;j<attrs.getLength();j++){
          Node attr=attrs.item(j);
          System.out.print(" The property is named :"+attr.getNodeName()+"    ");
          System.out.println(" Property value is :"+attr.getNodeValue());
        }
        // Get movie Element child node collection 
        NodeList childNodes=movie.getChildNodes();
        for(int k=0;k<childNodes.getLength();k++){
          Node child=childNodes.item(k);
          if (child.getNodeType()==Document.ELEMENT_NODE) {
            System.out.println(" Node name :"+child.getNodeName()+"    ");
            //System.out.println(" Node value :"+child.getNodeValue());
            System.out.println(" Node value :"+child.getFirstChild().getNodeValue());
          }
        }
        System.out.println(" No. 1 "+(i+1)+" The analysis of the film is over ");
      }
      System.out.println(" End of parsing --------------------------------");
    } catch (Exception e) {
      e.printStackTrace();
    }
2

Summarize


Related articles: