Android parsing xml

Source: Internet
Author: User
Tags closing tag xml parser

The XML file can be parsed on the Android platform using the simple API for XML (SAX), the document Object Model (DOM), and the pull parser included with Android.

Here is the XML file to parse for this example: Itcast.xml

<?xml version= "1.0" encoding= "UTF-8"?>
<persons>
<person id= ">"
<name> Li Ming </name>
<age>30</age>
</person>
<person id= ">"
<name> Li Xiangmei </name>
<age>25</age>
</person>
</persons>

The example defines a javabean for storing the XML content parsed above, the JavaBean is the person, the code:

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

1. Sax parsing xml file

Sax is a fast parsing and memory-intensive XML parser that is ideal for mobile devices such as Android. The Sax parsing XML file is event-driven, that is, it does not need to parse the entire document, and in the process of parsing the document in order of content, Sax determines whether the currently read character is a part of the valid XML syntax, and triggers the event if it conforms. The so-called events are actually some callback (callback) methods, which are defined in the ContentHandler interface.

public static list<person> ReadXML (InputStream instream) {
try {
Creating a parser
SAXParserFactory SPF = saxparserfactory.newinstance ();
SAXParser saxparser = Spf.newsaxparser ();

Set the correlation attribute of the parser, true to open the namespace attribute
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;
}


Sax class: DefaultHandler, which implements the ContentHandler interface. At the time of implementation, you simply inherit the class and overload the appropriate method.
public class Xmlcontenthandler extends DefaultHandler {

Private list<person> persons = NULL;
private person Currentperson;
Private String TagName = null;//The element label that is currently parsed

Public list<person> getpersons () {
return persons;
}

Receives notification of the beginning of a document. When you encounter the beginning of a document, call this method, where you can do some preprocessing work.
@Override
public void Startdocument () throws Saxexception {
persons = new arraylist<person> ();
}

The notification that the receive element starts. This method is triggered when a start tag is read. Where NamespaceURI represents the namespace of the element;
LocalName represents the local name of the element (without a prefix); QName represents the qualified name of the element (prefixed); Atts represents the collection of attributes for the 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;
}

A notification that receives character data. This method is used to process what is read in the XML file, and the first parameter is used to store the contents of the file.
The next two parameters are the starting position and the length of the read string in the array, and the content can be obtained using new string (Ch,start,length).
@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 notification at the end of the document. This method is called when the closing tag is encountered. Where the URI represents the namespace of the element;
LocalName represents the local name of the element (without a prefix); name denotes the qualified name of the element (prefixed)
@Override
public void EndElement (string uri, String localname, String name) throws Saxexception {

if (localname.equals ("person")) {
Persons.add (Currentperson);
Currentperson = null;
}

This.tagname = null;
}
}

2. DOM parsing xml file

When the DOM parses an XML file, it reads all the contents of the XML file into memory, and then allows you to use the DOM API to traverse the XML tree and retrieve the data you need. The code that uses the DOM to manipulate XML looks more intuitive and, in some ways, simpler than sax-based implementations. However, because the DOM needs to read all the contents of the XML file into memory, so the memory consumption is large, especially for mobile devices running Android, because the resources of the device is more valuable, so it is recommended to use Sax to parse the XML file, of course, It is possible to use the DOM if the content of the XML file is relatively small.

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");//Find All person nodes

for (int i = 0; i < items.getlength (); i++) {
person person = new person ();

Get the first person node
Element Personnode = (Element) items.item (i);

Gets the ID property value of the person node
Person.setid (New Integer (Personnode.getattribute ("id")));

Get all child nodes under the person node (white space 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); Determine if the element type

if (node.getnodetype () = = Node.element_node) {
Element Childnode = (element) node;

Determine if the name element
if ("Name". Equals (Childnode.getnodename ())) {
Gets the name element under the text node, and then gets the 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;
}

3.Pull Parser Parsing XML file

The pull parser operates in a similar way to the SAX parser. It provides similar events such as starting and ending element events, using Parser.next () to move to the next element and triggering the corresponding event. Events are sent as numeric codes, so you can use a switch to handle the events of interest. When the element begins parsing, the Parser.nexttext () method is called to get the value of the next text type element.

Read XML
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 processed
persons = new arraylist<person> ();
Break

Case xmlpullparser.start_tag://Start Element event
String name = Parser.getname ();
if (Name.equalsignorecase ("person")) {
Currentperson = new Person ();
Currentperson.setid (New Integer (Parser.getattributevalue (NULL, "id"));
} else if (Currentperson! = null) {
if (name.equalsignorecase ("name")) {
Currentperson.setname (Parser.nexttext ());//If the text element is followed, it returns its value
} else if (Name.equalsignorecase ("Age")) {
Currentperson.setage (New Short (Parser.nexttext ()));
}
}
Break

Case xmlpullparser.end_tag://End Element Event
if (Parser.getname (). Equalsignorecase ("person") && Currentperson! = null) {
Persons.add (Currentperson);
Currentperson = null;
}

Break
}

EventType = Parser.next ();
}

Instream.close ();
return persons;
} catch (Exception e) {
E.printstacktrace ();
}

return null;
}


into an XML file
Use the pull parser to generate a myitcast.xml file with the same contents as the Itcast.xml file.
public static String WriteXML (list<person> persons, writer writer) {

XmlSerializer serializer = Xml.newserializer ();

try {
Serializer.setoutput (writer);
Serializer.startdocument ("UTF-8", true);

The first parameter is a namespace and can be set to NULL if you do not use a namespace
Serializer.starttag ("", "persons");

for (person 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 want to get only the generated XML content, you can use StringWriter:
StringWriter writer = new StringWriter ();
WriteXML (persons, writer);
String content = writer.tostring ();

4.SAX and Pull use

The difference is that the SAX parser works by automatically pushing events into the event handler, so you can't control the active end of the event's processing, and the pull parser works by allowing your application code to proactively get events from the parser, just because it's actively getting events, Therefore, you can no longer get the event after the desired condition has been satisfied, ending the parsing.
You can find a sample of sax and pull comparison to find that pull is a while loop, can jump out at any time, and sax is not, sax is as long as the parsing, it must be resolved to complete.

Android parsing xml

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.