Piglet's Android starter Road Day 8 Part 1

Source: Internet
Author: User
Tags tagname

Piglet's Android starter Road Day 8 Part 1

Analysis of--xml file in Android network programming

---reprint please specify the Source: Coder-pig


Introduction to this section:

Unknowingly, this series of blog has been written to the 8th day, many friends feedback benefited a lot, to help you

I feel gratified, originally Day 8 is want to analyze the graphics and image processing of Android, but I want to go,

Or decided to first explain the network programming in Android, because a friend proposed to explain the network, so

In Day 8 we will analyze some of the applications of Android in the Web, and this blog is for beginners,

And in view of the author's level, so just analysis, not in-depth! In Day 8 We will explain some of the basic

Web applications, such as downloading data on the network, images, file Xml,json, building simple client-side and service-to-end intersection

Mutual wait! In Part 1 we will explain in detail the common methods of XML and parsing XML!



Learning Roadmap for this section:




The text of this section:


three ways Android interacts with the Internet:






An introduction to the XML file highlights:




comparison of common methods for parsing XML in Android:








Sax Parsing xml file:




The process of Sax parsing xml





Core code:

①saxservice.java:

Package Com.jay.example.service;import Java.util.arraylist;import Org.xml.sax.attributes;import Org.xml.sax.saxexception;import Org.xml.sax.helpers.defaulthandler;import Android.util.log;import Com.jay.example.bean.person;public class Saxservice extends defaulthandler{private person person;private ArrayList <Person> persons;//The element tag that is currently parsed private String TagName = null;//is triggered when read to the start of a document, and is typically done here with some initialization @overridepublic void Startdocument () throws saxexception {this.persons = new arraylist<person> (); LOG.I ("SAX", "read to document header, start parsing xml");} Called when a start tag is read, the second parameter is the signature, the last parameter is an array of attributes @overridepublic void startelement (String uri, String localname, String qName, Attributes Attributes) throws Saxexception {if (localname.equals ("person")} {person = new person ();p Erson.setid ( Integer.parseint (Attributes.getvalue ("id"))); LOG.I ("SAX", "read Tags");} This.tagname = LocalName;} The processing XML file reads to the content, the first parameter is the string content, followed by the starting position and length @overridepublic void characters (char[] ch, int start, int length) throws saxexception {//determines if the current label is valid if (This.tagName = null) {String data = new String (ch,start,length);//reads the contents of the label if (This.tagName.equals ("name")) { This.person.setName (data);} else if (this.tagName.equals ("Age")) {This.person.setAge (Integer.parseint (data));}} The end of the document section, where the object is added to the binding @overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {if ( Localname.equals ("person")) {This.persons.add (person);p Erson = null;} This.tagname = null;} Get persons Collection Public arraylist<person> Getpersons () {return persons;}}

the ReadXml () method in ②mainactivity:

Private Arraylist<person> ReadXml () throws exception{//gets the file resource to establish an input stream object InputStream is = Getassets (). Open (" Persons.xml ")//① create XML parsing processor Saxservice SS = new Saxservice ();//② get sax parsing factory SAXParserFactory factory = Saxparserfactory.newinstance ();//③ creates a sax parser saxparser parser = Factory.newsaxparser ();//④ assigns the XML parsing processor to the parser, parses the document, Send event to Processor Parser.parse (IS,SS); Is.close (); return ss.getpersons ();}






DOM parsing xml file



The flow of DOM parsing xml



Core code:

The DOM parses the XML code:

public static arraylist<person> Queryxml (context context) {arraylist<person> Persons = new arraylist< Person> (); try {//① get DOM Parser Factory Example: documentbuilderfactory dbfactory = Documentbuilderfactory.newinstance ();// ② gets the DOM parser from the DOM factory Documentbuilder Dbbuilder = Dbfactory.newdocumentbuilder ();//③ reads the XML file to parse into the DOM parser document DOC = Dbbuilder.parse (Context.getassets (). Open ("Persons2.xml")); System.out.println ("Domimplemention object to process the document =" + doc.getimplementation ());//④ gets the list of nodes for the element named person in the document nodelist NList = Doc.getelementsbytagname ("person");//⑤ iterates through the collection, displaying the elements in the collection and the names of the child elements for (int i = 0;i < Nlist.getlength (); i++) {// The element personelement = (Element) Nlist.item (i) is first parsed from the person elements. Person p = new person ();p. SetId (integer.valueof (Personelement.getattribute ("id")));// Gets the note collection for name and age under person nodelist childnolist = Personelement.getchildnodes (); for (int j = 0;j < Childnolist.getlength (); j + +) {Node Childnode = Childnolist.item (j);//Determines whether the child note type is an element NoteIf (childnode.getnodetype () = = Node.element_node) {ElemeNT Childelement = (Element) childnode;if ("Name". Equals (Childelement.getnodename ())) P.setname ( Childelement.getfirstchild (). Getnodevalue ()); else if ("Age". Equals (Childelement.getnodename ())) P.setage ( Integer.valueof (Childelement.getfirstchild (). Getnodevalue ()));}} Persons.add (P);}} catch (Exception e) {e.printstacktrace ();} return Persons;}





parsing an XML file using the Pull parser





Using code Examples:

To facilitate the presentation, three parsing methods are packaged into one program:

Parse the XML file in three different ways, and generate an XML file using the pull parser, in the data/data/< package name >/file Directory

The generated XML file can be found


:



Reference code: code Download














Piglet's Android starter Road Day 8 Part 1

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.