A summary of several methods for manipulating XML in Android _android

Source: Internet
Author: User
Tags throwable

As an industry-recognized data Interchange Format, XML is widely used and implemented in every platform and language. Its standard type, reliability, safety ... No doubt. On the Android platform, we often use XML data formats and XML files to implement data storage and data exchange.

tips:Android Storage data generally have the following: Sharedpreferences (parameterized), XML files, sqllite database, network, ContentProvider (content provider).

In Android, there are several ways to manipulate XML files: Sax operations, pull operations, DOM operations, and so on. The DOM approach, which may be the most familiar of all, is also in line with the standards of the consortium.

1)

In the Java platform, there are excellent open source packages such as dom4j, which greatly facilitates the use of DOM standards to manipulate XML files. In JavaScript, different browser resolution engines have a slight difference in the parsing and operation of the DOM (though this is not the focus of this chapter). The way DOM is, it has its drawbacks. The XML file is usually loaded at once and then parsed using the DOM API, which consumes a large amount of memory and has a certain impact on performance. And our Android phone, although configured in a constant upgrade, but the memory side, temporarily not comparable to the traditional PC. So, on Android, it's not recommended to use DOM to parse and manipulate XML.

Copy Code code as follows:

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 (InputStream stream) throws Throwable
{
List<person> list =new arraylist<person> ();
Documentbuilderfactory factory =documentbuilderfactory.newinstance ();
Documentbuilder builder =factory.newdocumentbuilder ();
The Document dom = Builder.parse (stream);//parsing completes and is stored in memory as a DOM tree. Compare consumption performance
Start using the DOM API to parse
Element root = Dom.getdocumentelement ();//root element
NodeList personnodes = root.getelementsbytagname ("person");//return all person element nodes
Start traversing.
for (int i=0;i<personnodes.getlength (); i++)
{
Person =new person ();
Element personelement = (Element) personnodes.item (i);
Person.setid (Personelement.getattribute ("id")),//Assign the value of the attribute node ID of the person element node to the person object
NodeList personchildrennodes =personelement.getchildnodes ();//Get all child nodes of the person node
Traverse all child nodes
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)
{
Child node--element node
Element Childnode = (Element) Personchildrennodes.item (j);
if ("Name". Equals (Childnode.getnodename ()))
{
If the name of the child node is "name." Assign the value of the first child node of the child element node to the person object
Person.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 very broad XML parsing standard that typically uses the handler pattern to process XML documents, which is very different from our usual habit of understanding There are often friends who find it difficult to understand when they first touch sax. In fact, sax is not complicated, just a way of thinking, as its name indicates, in order for us to deal with XML documents in a simpler way, let's start with the following.

Copy Code code as follows:

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) throws Throwable
{
SAXParserFactory factory = Saxparserfactory.newinstance ()//Factory mode or single case 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 Attributes) throws Saxexception {
if ("Person". Equals (LocalName))
{
The XML element node is triggered at the start, is "person"
person = new person ();
Person.setid (New Integer (Attributes.getvalue (0));
}
Tag =localname;//save element node name
}
@Override
public void EndElement (string uri, String localname, String qName)
Throws Saxexception {
Trigger at end of element node, 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 and is lightweight parsing, embedded in the Android kernel pull, so we don't need to add a third-party jar pack to support pull. Pull parsing and sax parsing are not the same places have (1) pull after reading the XML file, triggering the corresponding event invocation method returns the number (2) pull can control where you want to parse it in the program to stop parsing.

Copy Code code as follows:

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 XML file
public static void SaveXML (List<person> list,writer write) throws Throwable
{
XmlSerializer serializer =xml.newserializer ();//serialization
Serializer.setoutput (write);//output stream
Serializer.startdocument ("UTF-8", true);//Start document
Serializer.starttag (NULL, "persons");
Loop to add person
for (person Person:list) {
Serializer.starttag (null, "person");
Serializer.attribute (NULL, "id", Person.getid (). toString ());//Set ID property and property value
Serializer.starttag (NULL, "name");
Serializer.text (Person.getname ());//text value of text node--name
Serializer.endtag (NULL, "name");
Serializer.starttag (NULL, "age");
Serializer.text (Person.getage (). toString ());//text node text value--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 parser =xml.newpullparser ();
Parser.setinput (Stream, "UTF-8");
int type =parser.geteventtype ();//Generate first Event
Loop as long as the current event type is not "end document"
while (type!=xmlpullparser.end_document)
{
Switch (type) {
Case Xmlpullparser.start_document:
List = new arraylist<person> ();
Break

Case Xmlpullparser.start_tag:
String name=parser.getname ()//Gets the element name that the parser is currently pointing to
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 that the parser is currently pointing to
}
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 ()//Don't forget this sentence.
}
return list;
}
}


The following is the code for the person class of the model layer:
Copy Code code as follows:

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


@Override
Public String toString () {
Return ' person [id= + ID + ', name= ' + name + ', age= ' + Age + '] ';
}

}

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.