Android XML Parsing

Source: Internet
Author: User
Tags tagname xml parser

On the Android platform, you can use simple API for XML (SAX), Document Object Model (DOM), and the pull parser that comes with Android to parse XML files.

The XML file to be parsed in this example is as follows:

File Name: itcast. xml

<? XML version = "1.0" encoding = "UTF-8"?>

<Persons>

<Person id = "23">

<Name> Li Ming </Name>

<Age> 30 </age>

</Person>

<Person id = "20">

<Name> Li xiangmei </Name>

<Age> 25 </age>

</Person>

</Persons>

The example defines a Javabean to store the XML content parsed above. The Javabean is person and the code is as follows:

Public class person {

Private integer ID;

Private string name;

Private short age;

Public integer GETID (){

Return ID;

}

Public void setid (integer ID ){

This. ID = ID;

}

Public String getname (){

Return name;

}

Public void setname (string name ){

This. Name = Name;

}

Public short getage (){

Return age;

}

Public void setage (short age ){

This. Age = age;

}

}

Use Sax to read XML files

Sax is an XML parser with high resolution speed and low memory usage. It is suitable for Android and other mobile devices.An event-driven file is used to parse an XML file. That is to say, it does not need to parse a complete file. In the process of parsing a document in order of content, sax checks whether the currently read characters are valid for a part of the XML syntax. If yes, the event is triggered. The so-called events are actually some callback methods, which are defined in the contenthandler interface.

Below are some common contenthandler interface methods:

  • Startdocument ()When a document starts, call this method to perform preprocessing.
  • Enddocument ()In contrast to the above method, when the document ends, you can call this method to do some aftercare work.
  • Startelement (string namespaceuri, string localname, string QNAME, attributes ATTS)This method is triggered when a start tag is read. Namespaceuri is the namespace, localname is the tag name without the namespace prefix, and QNAME is the tag name with the namespace prefix. You can use ATTS to obtain all the attribute names and corresponding values. It should be noted that an important feature of Sax is its stream processing. When a tag is encountered, it will not record the previously encountered tag, that is, in startelement () all the information you know in the method is the name and attribute of the tag. As for the nested structure of the tag, the name of the Upper-layer tag, whether there is sub-meta, and other information related to the structure, they are all unknown, and they all need your program to complete. This makes it easier to program and process sax than Dom.
  • Endelement (string Uri, string localname, string name)This method corresponds to the above method and calls this method when an end tag is encountered.
  • Characters (char [] CH, int start, int length)This method is used to process the content read in the XML file. The first parameter is used to store the content of the file. The next two parameters are the start position and length of the read string in this array, use new string (CH, start, length) to obtain the content.

The event triggered by parsing itcast. XML is:

Trigger events of read tags and content

{Document start} startdocument ()

<Persons> startelement (, "persons", null, "{attributes }")

"\ N \ t" characters ("<persons>... </persons>", "12", "2 ")

<Person> startelement (, "person", null, "{attributes }")

"\ N \ t" characters ("<persons>... </persons>", "31", "3 ")

<Name> startelement (, "name", null, "{attributes }")

"Li Ming" characters ("<persons>... </persons>", "40", "2 ")

</Name> endelement ("", "name", null)

"\ N \ t" characters ("<persons>... </persons>", "50", "3 ")

<Age> startelement (, "Age", null, "{attributes }")

"30" characters ("<persons>... </persons>", "58", "2 ")

</Age> endelement ("", "Age", null)

"\ N \ t" characters ("<persons>... </persons>", "67", "2 ")

</Person> endelement ("", "person", null)

"\ N \ t" characters ("<persons>... </persons>", "79", "2 ")

<Person> startelement (, "person", null, "{attributes }")

"\ N \ t" characters ("<persons>... </persons>", "98", "3 ")

<Name> startelement (, "name", null, "{attributes }")

"Li xiangmei" characters ("<persons>... </persons>", "107", "3 ")

</Name> endelement ("", "name", null)

"\ N \ t" characters ("<persons>... </persons>", "118", "3 ")

<Age> startelement (, "Age", null, "{attributes }")

"25" characters ("<persons>... </persons>", "126", "2 ")

</Age> endelement ("", "Age", null)

"\ N \ t" characters ("<persons>... </persons>", "135", "2 ")

</Person> endelement ("", "person", null)

"\ N" characters ("<persons>... </persons>", "147", "1 ")

</Persons> endelement ("", "persons", null)

{Document end} enddocument ()

As long as the contenthandler interface class is provided for sax, the class will be notified (in fact, Sax calls the callback method in this class ).Contenthandler is an interface that may be inconvenient to use. Therefore, Sax also sets a helper class for it: defaulthandler, which implements this interface, however, all its method bodies are empty. During implementation, you only need to inherit the class and then reload the corresponding method.. The code for parsing itcast. XML using Sax is as follows:

Public static list <person> readxml (inputstream instream ){

Try {

Saxparserfactory SPF = saxparserfactory. newinstance ();

Saxparser = SPF. newsaxparser (); // create a parser

// Set attributes related to the parser. http://xml.org/sax/features/namespaces = true indicates enabling the namespace feature

Saxparser. setproperty ("http://xml.org/sax/features/namespaces", true );

Xmlcontenthandler handler = new xmlcontenthandler ();

Saxparser. parse (instream, Handler );

Instream. Close ();

Return handler. getpersons ();

} Catch (exception e ){

E. printstacktrace ();

}

Return NULL;

}

Import java. util. arraylist;

Import java. util. List;

Import org. xml. Sax. attributes;

Import org. xml. Sax. saxexception;

Import org. xml. Sax. helpers. defaulthandler;

Import CN. itcast. xml. domain. person;

Public class xmlcontenthandler extends defaulthandler {

Private list <person> Persons = NULL;

Private person currentperson;

Private string tagname = NULL; // The element tag currently parsed

Public list <person> getpersons (){

Return persons;

}

/*

* Receives notifications of the beginning of a document.

*/

@ Override public void startdocument () throws saxexception {

Persons = new arraylist <person> ();

}

/*

* Receives notifications of character data.

*/

@ Override public void characters (char [] CH, int start, int length) throws saxexception {

If (tagname! = NULL ){

String data = new string (CH, start, length );

If (tagname. Equals ("name ")){

This. currentperson. setname (data );

} Else if (tagname. Equals ("Age ")){

This. currentperson. setage (short. parseshort (data ));

}

}

}

/*

* Receives notifications starting with an element.

* The parameter meaning is as follows:

* Namespaceuri: namespace of an element

* Localname: The local name of the element (without the prefix)

* QNAME: the qualified name (with prefix) of the element)

* ATTS: An Attribute Set of an element.

*/

@ Override public void startelement (string namespaceuri, string localname, string QNAME, attributes ATTS) throws saxexception {

If (localname. Equals ("person ")){

Currentperson = new person ();

Currentperson. setid (integer. parseint (ATTS. getvalue ("ID ")));

}

This. tagname = localname;

}

/*

* Receive notifications at the end of a document.

* The parameter meaning is as follows:

* URI: The namespace of the element.

* Localname: The local name of the element (without the prefix)

* Name: the qualified name (with a prefix) of the element)

*

*/

@ Override public void endelement (string Uri, string localname, string name) throws saxexception {

If (localname. Equals ("person ")){

Persons. Add (currentperson );

Currentperson = NULL;

}

This. tagname = NULL;

}

}

Use Dom to read XML files

In addition to using Sax to parse XML files, you can also use the familiar Dom to parse XML files. When the DOM parses an XML file, it reads all the content of the XML file to the memory, and then allows you to use the dom api to traverse the XML tree and retrieve the required data. The code that uses Dom to operate XML looks intuitive and is simpler than the implementation based on sax in some aspects. However, because the Dom needs to read all the content of the XML file into the memory, the memory consumption is relatively large, especially for mobile devices running Android, because the device resources are precious, we recommend that you use SAX to parse XML files. Of course, it is feasible to use Dom if the content of the XML file is small.

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. xml. domain. person;

/**

* Use Dom to parse XML files

*

*/

Public class domxmlreader {

Public static list <person> readxml (inputstream instream ){

List <person> Persons = new arraylist <person> ();

Documentbuilderfactory factory = documentbuilderfactory. newinstance ();

Try {

Documentbuilder builder = factory. newdocumentbuilder ();

Document dom = builder. parse (instream );

Element root = Dom. getdocumentelement ();

Nodelist items = root. getelementsbytagname ("person"); // query all person nodes

For (INT I = 0; I <items. getlength (); I ++ ){

Person = new person ();

// Obtain the first person Node

Element personnode = (element) items. item (I );

// Obtain the ID attribute value of the person Node

Person. setid (New INTEGER (personnode. getattribute ("ID ")));

// Obtain all subnodes under the person node (blank nodes and Name/age elements between labels)

Nodelist childsnodes = personnode. getchildnodes ();

For (Int J = 0; j <childsnodes. getlength (); j ++ ){

Node node = (node) childsnodes. Item (j); // determines whether the element type is used.

If (node. getnodetype () = node. element_node) {element childnode = (element) node;

// Determine whether the name element is used

If ("name". Equals (childnode. getnodename ())){

// Obtain the text node under the name element, and then obtain data from the text node

Person. setname (childnode. getfirstchild (). getnodevalue ());

} Else if ("Age". Equals (childnode. getnodename ())){

Person. setage (new short (childnode. getfirstchild (). getnodevalue ()));

}

}

}

Persons. Add (person );

}

Instream. Close ();

} Catch (exception e ){

E. printstacktrace ();

}

Return persons;

}

Use the pull parser to read XML files

In addition to using Sax and Dom to parse XML files, you can also use the android built-in pull parser to parse XML files.The Running Method of the pull parser is similar to that of the SAX Parser. It provides similar events, such as the start element and end element events. You can use parser. Next () to enter the next element and trigger the corresponding event. The event is sent as a numeric code, so you can use a switch to process the event you are interested in. When parsing an element, call parser. nexttext () to obtain the value of the next text element.

Pull parser source code and documentation download URL: http://www.xmlpull.org/

Import org. xmlpull. v1.xmlpullparser;

Import Android. util. xml;

Import CN. itcast. xml. domain. person;

Public class pullxmlreader {

Public static list <person> readxml (inputstream instream ){

Xmlpullparser parser = xml. newpullparser ();

Try {

Parser. setinput (instream, "UTF-8 ");

Int eventtype = parser. geteventtype ();

Person currentperson = NULL;

List <person> Persons = NULL;

While (eventtype! = Xmlpullparser. end_document ){

Switch (eventtype ){

Case xmlpullparser. start_document: // document start event. Data initialization can be performed.

Persons = new arraylist <person> ();

Break;

Case xmlpullparser. start_tag: // start element event

String name = parser. getname ();

If (name. inclusignorecase ("person ")){

Currentperson = new person ();

Currentperson. setid (New INTEGER (parser. getattributevalue (null, "ID ")));

} Else if (currentperson! = NULL ){

If (name. inclusignorecase ("name ")){

Currentperson. setname (parser. nexttext (); // if it is followed by a text element, its value is returned.

} Else if (name. Your signorecase ("Age ")){

Currentperson. setage (new short (parser. nexttext ()));

}

}

Break;

Case xmlpullparser. end_tag: // End Element event

If (parser. getname (). inclusignorecase ("person") & currentperson! = NULL ){

Persons. Add (currentperson );

Currentperson = NULL;

}

Break;

}

Eventtype = parser. Next ();

}

Instream. Close ();

Return persons;

} Catch (exception e ){

E. printstacktrace ();

}

Return NULL;

}

}

Use the pull parser to generate an XML file

Sometimes, we need to generate an XML file,There are many ways to generate an XML file. For example, you can use only one stringbuilder group to splice XML content and then write the content into the file. Or, you can use Dom APIs to generate an XML file, alternatively, you can use the pull parser to generate an XML file. We recommend that you use the pull parser.

Use the pull parser to generate a myitcast. xml file with the same content as the itcast. xml file.

Public static string writexml (list <person> persons, writer ){

Xmlserializer serializer = xml. newserializer ();

Try {

Serializer. setoutput (writer );

Serializer. startdocument ("UTF-8", true );

// The first parameter is the namespace. If the namespace is not used, you can set it to null.

Serializer. starttag ("", "persons ");

For (person: Persons ){

Serializer. starttag ("", "person ");

Serializer. Attribute ("", "ID", person. GETID (). tostring ());

Serializer. starttag ("", "name ");

Serializer. Text (person. getname ());

Serializer. endtag ("", "name ");

Serializer. starttag ("", "Age ");

Serializer. Text (person. getage (). tostring ());

Serializer. endtag ("", "Age ");

Serializer. endtag ("", "person ");

}

Serializer. endtag ("", "persons ");

Serializer. enddocument ();

Return writer. tostring ();

} Catch (exception e ){

E. printstacktrace ();

}

Return NULL;

}

Use the following code to generate an XML file ):

File xmlfile = new file ("myitcast. xml ");

Fileoutputstream outstream = new fileoutputstream (xmlfile );

Outputstreamwriter outstreamwriter = new outputstreamwriter (outstream, "UTF-8 ");

Bufferedwriter writer = new bufferedwriter (outstreamwriter );

Writexml (persons, writer );

Writer. Flush ();

Writer. Close ();

If you only want to get the generated XML content, you can use stringwriter:

Stringwriter writer = new stringwriter ();

Writexml (persons, writer );

String content = writer. tostring ();

 

Source code download: http://dl.dbank.com/c0glt5uic5

Note: Open ddms to view the read result.

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.