Summary of three XML operations for android

Source: Internet
Author: User
In android, there are several methods to operate xml files: SAX operations, Pull operations, and DOM operations. Among them, the DOM method may be the most familiar to everyone. it is also in line with W3C standards in android, operating xml files, there are generally several ways: SAX operations, Pull operations, DOM operations and so on. Among them, the DOM method may be the most familiar and compliant with W3C standards.

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:In android, data is stored in the following types: SharedPreferences (parameterization), XML files, sqllite databases, networks, and ContentProvider.

In android, there are several methods to operate xml files: SAX operations, Pull operations, and DOM operations. Among them, the DOM method may be most familiar to everyone and also complies with W3C standards.

1)

On the java platform, there are excellent open-source packages such as DOM4J, which greatly facilitates you to use DOM standards 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, we do not recommend using DOM to parse and operate XML on android.

The code is 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
 
  
GetPersons (InputStream stream) throws Throwable {List
  
   
List = new ArrayList
   
    
(); 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
    
     


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.

The code is 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
      
       
GetPersons (InputStream inStream) throws Throwable {SAXParserFactory factory = SAXParserFactory. newInstance (); // is the 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
       
        
List = null; Person person = null; private String tag = null; public List
        
         
GetPerson () {return list;} @ Override public void startDocument () throws SAXException {list = new ArrayList
         
          
() ;}@ Override public void startElement (String uri, String localName, String qName, Attributes 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 localName, String qName) throws SAXException {// triggered when the element node ends Sent, 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.

The code is 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 the xml file public static void saveXML (List
      
       
List, Writer write) throws Throwable {XmlSerializer serializer = Xml. newSerializer (); // serialize serializer. setOutput (write); // output stream serializer. startDocument ("UTF-8", true); // starts the document serializer. startTag (null, "persons"); // cyclically add person for (Person 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 (null, "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
       
        
GetPersons (InputStream stream) throws Throwable {List
        
         
List = null; Person person = null; XmlPullParser parser = 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
         
          
(); 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:

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

The above is the detailed summary of the three XML operations for android. For more information, see other related articles in the first PHP community!

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.