Android XML operations

Source: Internet
Author: User

As an industry-recognized data exchange format, XML is widely used and implemented on various platforms and languages. Its standard type, reliability, and security... beyond all doubt. On the Android platform, we often use XML data formats and XML files to implement data storage and data exchange.

TIPS: Generally, data stored in android can be sharedpreferences (parameterization), XML files, sqllite databases, networks, and contentprovider.

 

In Android, there are several methods to operate XML files:Sax operations, pull operations, Dom operations, etc.. Among them, the DOM method may be most familiar to everyone and also complies with W3C standards.

1)

On the Java platformDom4jSuch an excellent open-source package greatly facilitates you to use the DOM standard to operate XML files. In JavaScript, different browser parsing engines have slightly different Dom parsing and operations (but this is not the focus of this chapter ). The DOM method also has its disadvantages. Generally, XML files are loaded at a time and parsed using Dom APIs. This consumes a lot of memory and affects the performance. Although our Android mobile phone is constantly being upgraded, its memory is not comparable to the traditional PC. Therefore, in Android development, I personally do not recommend using Dom to parse and operate 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 (inputstrea M stream) throws throwable {list <person> List = new arraylist <person> (); documentbuilderfactory factory = documentbuilderfactory. newinstance (); documentbuilder builder = factory. newdocumentbuilder (); document dom = builder. parse (Stream); // The parsing is complete and stored in the memory as a DOM tree. Performance consumption // start to use Dom APIs to parse element root = Dom. getdocumentelement (); // The root element nodelist personnodes = root. getelementsbytagname ("person"); // return all the person element nodes // start traversing for (INT I = 0; I <personnodes. getlength (); I ++) {person = new person (); element personelement = (element) personnodes. item (I); person. setid (New INTEGER (personelement. getattribute ("ID"); // assign the value of the property node ID of the person element node to the person object nodelist personchildrennodes = personelement. getchildnodes (); // obtain all subnodes of the person node // traverse all subnodes for (Int J = 0; j <personchildrennodes. getlength (); j ++) {// determines 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) {// subnode -- Element Node element childnode = (element) personchildrennodes. item (j); If ("name ". equals (childnode. getnodename () {// If the subnode name is "name ". assign the value of the first subnode of the child element node to the person object. 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. It usually uses the handler mode to process XML documents. This processing mode is very different from what we usually get used, some friends around me often feel a little difficult to understand when they are new to sax. In fact, Sax is not complicated, but it is a different way of thinking. As its name indicates, in order to make it easier for us to process XML documents, let's get started.

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) THR Ows 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 = 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) throws saxexception {If ("person ". equals (localname) {// triggered when the XML Element Node starts, 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 local Name, string QNAME) throws saxexception {// triggered when the Element Node ends. It is "person" If ("person ". equals (localname) {list. add (person); person = NULL;} tag = NULL; // At the end, you need to clear the 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. It is both lightweight and has been embedded in the android kernel. Therefore, we do not need to add a third-party jar package to support pull. Pull Parsing is different from sax parsing. (1) Pull reads the XML file and triggers the corresponding event. The call method returns a number (2) pull can control in the program where the parsing can be stopped.

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 the XML file public static void savexml (list <person> list, writer write) throws throwable {xmlserializer serializer = xml. n Ewserializer (); // serialize serializer. setoutput (write); // output stream serializer. startdocument ("UTF-8", true); // starts the document serializer. starttag (null, "persons"); // cyclically add person for (person: List) {serializer. starttag (null, "person"); serializer. attribute (null, "ID", person. GETID (). tostring (); // set the ID attribute and attribute value serializer. starttag (null, "name"); serializer. text (person. getname (); // text value of the text node -- name serializer. endtag (NUL L, "name"); serializer. starttag (null, "Age"); serializer. text (person. getage (). tostring (); // 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 = NULL; xmlpullparser P Arser = xml. newpullparser (); parser. setinput (stream, "UTF-8"); int type = parser. geteventtype (); // generates the first event // as long as the current event type is not "End Document", the loop while (type! = Xmlpullparser. end_document) {Switch (type) {Case xmlpullparser. start_document: List = new arraylist <person> (); break; Case xmlpullparser. start_tag: string name = parser. getname (); // get 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 text value of the next text node of the element currently directed by the parser} 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 (); // do not forget this sentence} return list ;}}


The following is the model-layer person class code:

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;}@Overridepublic String toString() {    return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";}}


After reading the examples in this article, I believe you have understood several ways to access and operate XML data in Android. Readers may wish to use the simulator to perform unit tests easily by tapping the code and debugging.

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.