Three kinds of parsing methods for Android XML data _android

Source: Internet
Author: User
Tags xml parser

This article contains the following content:

DOM parsing of XML data
Sax parsing of XML data
Pull parsing of XML data
Three kinds of resolution used in activity
The difference between Sax parsing and pull parsing

Three ways to resolve the process:

1. Simulate the creation of XML data in the Assets folder
2. Create a Bean object corresponding to the XML
3. Start parsing

DOM parsing of XML data

When the DOM parses an XML file, it reads all the contents of the XML file into memory (memory is much more consumed), and then allows you to traverse the XML tree using the DOM API and retrieve the required data

I. Simulate the creation of an XML file in the Assets folder

<students>
 <student>
  <name sex= "man" > Xiaoming </name>
  <nickName> mingming </ nickname>
 </student>
 <student>
  <name sex= "Woman" > Little Red </name>
  < nickname> Red </nickName>
 </student>
 <student>
  <name sex= "man" > Small bright </name >
  <nickName> Bright </nickName>
 </student>
</students>

Second, create the corresponding XML Bean object

public class Student {
 private String name;
 Private String sex;
 Private String nickname;

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

 Public String Getnickname () {return
  nickname;
 }

 public void Setnickname (String nickname) {
  this.nickname = nickname;
 }

 @Override public
 String toString () {return
  "student{" +
    "name= '" + name + ' \ ' +
    ", sex= ' + sex + ' \ ' + '
    , nickname= ' "+ nickname + ' \ ' + '
    } ';
 }
}

Third, Dom parsing

Public list<student> Dom2xml (InputStream is) throws Exception {//series of initialization list<student> List = new Arraylis
 T<> ();
 Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
 Documentbuilder builder = Factory.newdocumentbuilder ();
 Obtain Document Object document = Builder.parse (IS);
 Obtain student list NodeList studentlist = document.getElementsByTagName ("student"); Traversal student label for (int i = 0; i < studentlist.getlength (); i++) {//Get student tag Node node_student = studentlist.it
  EM (i);
  Get the label inside the student tag nodelist childnodes = Node_student.getchildnodes ();
  New Student object Student Student = new Student (); Iterate through the tags inside the student tag for (int j = 0; J < Childnodes.getlength (); j + +) {//Get name and nickname tag Node childnode = Chil
   Dnodes.item (j);
    Determines whether name or nickname if ("Name". Equals (Childnode.getnodename ()) {String name = Childnode.gettextcontent ();
    Student.setname (name); Gets the property of name NamedNodeMap nnm = Childnode.getattRibutes ();
    Gets the Sex property, which takes 0 Node n = nnm.item (0), because there is only one property;
   Student.setsex (N.gettextcontent ());
    else if ("nickname". Equals (Childnode.getnodename ()) {String nickname = Childnode.gettextcontent ();
   Student.setnickname (nickname);
 }//Add to List List.add (student);
} return list;

 }

Sax parsing of XML data

Sax is an XML parser that is fast and consumes less memory, and Sax parses XML files using event-driven, which does not need to parse the entire document, but rather the process of parsing the document in the order of content

Since the steps in the previous one and two are the same, here we omit the

Three, sax analysis

Public list<student> Sax2xml (InputStream is) throws Exception {SAXParserFactory SPF = Saxparserfactory.newinstanc
 E ();
 Initializes the SAX parser SAXParser sp = Spf.newsaxparser ();
 New resolution processor MyHandler handler = new MyHandler ();
 Handing resolution to the processor Sp.parse (is, handler);
Returns list return handler.getlist ();
 public class MyHandler extends DefaultHandler {private list<student> List;
 Private Student Student;

 Used to store a read temporary variable private String tempstring; 
  /** * Parsing to the beginning of the document call, generally do initialization operation * * @throws saxexception/@Override public void Startdocument () throws Saxexception {
  List = new arraylist<> ();
 Super.startdocument (); /** * resolves to the end of the document call, generally do the recycle operation * * @throws saxexception * * * @Override public void enddocument () throws Saxexception
 {super.enddocument (); /** * Call this method * @param uri * @param localname * @param qName * @param attributes * @throws Saxex * For each element read Ception/@Override public void startelement (string uri, String localname, String QnamE, Attributes Attributes) throws Saxexception {if ("Student". Equals (QName)) {//read to student tag student = new Student
  ();
   else if ("name". Equals (QName)) {//Get the property String sex = Attributes.getvalue ("Sex") inside the name;
  Student.setsex (Sex);
 } super.startelement (URI, LocalName, qName, attributes); /** * Read to the end of the element call * * @param URI * @param localname * @param qName * @throws saxexception * * @Override P
   ublic void EndElement (String uri, String localname, String qName) throws Saxexception {if ("Student". Equals (QName)) {
  List.add (student);
  } if ("Name". Equals (QName)) {student.setname (tempstring);
  else if ("nickname". Equals (QName)) {student.setnickname (qName);
 } super.endelement (URI, LocalName, QName);  /** * Read to attribute content call * * @param ch * @param start * @param length * @throws saxexception/@Override Public void characters (char[] ch, int start, int length) throws saxexception {tempstring = new String (CH, start, length);
 Super.characters (CH, start, length);
 /** * Get the list * * @return/public list<student> getlist () {return list;

 }
}

Pull parsing of XML data

The pull parser runs the same way as the SAX parser. It provides a similar event that you can use a switch to handle events of interest

Third, pull analysis

Public list<student> Pull2xml (InputStream is) throws Exception {list<student> List = null;
 Student Student = null;
 Create Xmlpull parser Xmlpullparser parser = Xml.newpullparser ();
 Initializes the Xmlpull parser parser.setinput (IS, "utf-8");
 Read the file type int type = Parser.geteventtype ();
    Infinite judgment file type read while (type!= xmlpullparser.end_document) {switch (type) {//Start label case XMLPULLPARSER.START_TAG:
    if ("Students". Equals (Parser.getname ())) {list = new arraylist<> ();
    else if ("Student". Equals (Parser.getname ()) {student = new student ();
     else if ("name". Equals (Parser.getname ()) {//Get sex property String sex = Parser.getattributevalue (null, "sex");
     Student.setsex (Sex);
     Gets the name value String name = Parser.nexttext ();
    Student.setname (name);
     else if ("nickname". Equals (Parser.getname ()) {//Get nickname value String nickname = Parser.nexttext ();
    Student.setnickname (nickname);
   } break; End Tag Case XmlpullpaRser.
    End_tag:if ("Student". Equals (Parser.getname ())) {List.add (student);
  } break;
 //Continue reading Tag type = Parser.next ();
} return list;

 }

use three kinds of resolution

in activity

public class Xmlactivity extends Appcompatactivity implements View.onclicklistener {private TextView TV;
 Private Button Bt_dom, Bt_sax, Bt_pull;
 Private Xmlutils xmlutils;

 Private list<student> students;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

  Setcontentview (R.layout.activity_xml);
  TV = (TextView) Findviewbyid (r.id.tv);
  Bt_dom = (Button) Findviewbyid (r.id.bt_dom);
  Bt_sax = (Button) Findviewbyid (r.id.bt_sax);

  Bt_pull = (Button) Findviewbyid (r.id.bt_pull);
  Bt_dom.setonclicklistener (this);
  Bt_sax.setonclicklistener (this);

  Bt_pull.setonclicklistener (this);
 Xmlutils = new Xmlutils (); @Override public void OnClick (View v) {switch (V.getid ()) {case R.id.bt_dom:try {students = Xmlutil
     S.dom2xml (Getresources (). Getassets (). Open ("Student.xml");
    Tv.settext (Students.tostring ());
    catch (Exception e) {e.printstacktrace ();
   } break;
    Case R.id.bt_sax:try {students = Xmlutils.sax2xml (Getresources (). Getassets (). Open ("Student.xml"));
    Tv.settext (Students.tostring ());
    catch (Exception e) {e.printstacktrace ();
   } break;
     Case R.id.bt_pull:try {students = Xmlutils.pull2xml (Getresources (). Getassets (). Open ("Student.xml"));
    Tv.settext (Students.tostring ());
    catch (Exception e) {e.printstacktrace ();
  } break;

 }
 }
}

The three resolution methods have the same effect picture


The difference between Sax parsing and pull parsing

The difference between sax and pull: The SAX parser works by automatically pushing events into the event handler, so you can't control the active end of the event, and the pull parser works to allow your application code to take the event from the parser actively because it is an active fetch event. Therefore, you can no longer get the event and end the resolution if the required conditions are met.

Source: Http://xiazai.jb51.net/201611/yuanma/AndroidXmljiexi (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.