When we are working on android projects, it will certainly involve parsing xml files. Next we will introduce the parsing of xml files, including DOM, SAX, Pull, and previously used DOM4J and JDOM:
XML file to be parsed: person. xml
zhangsan
25
lisi
23
Create person entity class:
package cn.itcast.domain;public class Person {private Integer id;private String name;private Short age;public Person(){}public Person(Integer id, String name, Short age) {this.id = id;this.name = name;this.age = 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;}@Overridepublic String toString() {return "Person [age=" + age + ", id=" + id + ", name=" + name + "]";}}
1. DOM parsing XML: DOM parsing loads all XML files, assembles them into a dom tree, And parses xml files through the relationship between nodes and nodes.
Public static List
GetPersons (InputStream inStream) throws Throwable {List
Persons = new ArrayList
(); // Create the parser factory DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance (); // create the parser DocumentBuilder builder = factory. newDocumentBuilder (); // create a Document tree model. All nodes are included in the Document object in a certain order. // they are arranged in a tree structure, all subsequent operations on the XML Document will be irrelevant to the parser Document parser net = builder. parse (inStream); // obtain the root Element root = javasnet. getDocumentElement (); // obtain the "person" node list under the root element. NodeList personNodes = root. getElementsByTagName ("person"); for (int I = 0; I <personNodes. getLength (); I ++) {Person person Person = new Person (); // obtain the Element personElement = (Element) personNodes in the node. item (I); // obtain the id attribute person in person. setId (new Integer (personElement. getAttribute ("id"); // obtain the subnode NodeList personChilds = personElement under the person node. getChildNodes (); for (int y = 0; y <personChilds. getLength (); y ++) {if (personChilds. item (y ). getNodeType () = Node. ELEMENT_NODE) {// determine whether the current node is Element type node Element childElement = (Element) personChilds. item (y); if ("name ". equals (childElement. getNodeName () {// obtain the value of the corresponding element person. setName (childElement. getFirstChild (). getNodeValue ();} else if ("age ". equals (childElement. getNodeName () {person. setAge (new Short (childElement. getFirstChild (). getNodeValue () ;}} persons. add (person);} return persons ;}
2. SAX parsing XML: It reads XML files sequentially without loading the entire file at a time. Due to limited memory resources of mobile devices, the SAX sequential reading method is more suitable for mobile development.
Public List
GetPersons (InputStream inStream) throws Throwable {// create SAXParserFactorySAXParserFactory factory = SAXParserFactory. newInstance (); // create the SAX parser SAXParser parser = factory. newSAXParser (); // create the XML parsing processor PersonParser personParser = new PersonParser (); // assign the XML parsing processor to the parser to parse the document, send each event to the processor parser. parse (inStream, personParser); inStream. close (); return personParser. getPersons ();} // defines the resolution processor private final class PersonParser extends DefaultHandler {private List
Persons = null; // put the parsed data in the List set private String tag = null; // define the label name private Person person = null for a global variable; public List
GetPersons () {return persons;} // parse Document @ Overridepublic void startDocument () throws SAXException {// parse
Partial persons = new ArrayList
() ;}@ Overridepublic void endDocument () throws SAXException {System. out. println ("end parse xml");}/*** parse Element * namespaceURI namespace * localName without prefix
---> Person * qName with prefix section ----> abc: worker * attributes Attribute Set ----> id = "001 ".... * // @ Overridepublic void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {// resolution
Some if ("person ". equals (localName) {person = new Person (); person. setId (new Integer (attributes. getValue (0);} tag = localName;} @ Overridepublic void characters (char [] ch, int start, int length) throws SAXException {// parse the text
Zhangsan
--> Zhangsanif (tag! = Null) {String data = new String (ch, start, length); // obtain the data of the text node if ("name ". equals (tag) {person. setName (data);} else if ("age ". equals (tag) {person. setAge (new Short (data) ;}}// resolution End Element @ Overridepublic void endElement (String uri, String localName, String qName) throws SAXException {if ("person ". equals (localName) {persons. add (person); person = null;} tag = null ;}}
3. pull parsing XML: pull Parsing is similar to SAX parsing, and both are lightweight parsing. pull has been embedded in the android kernel, so we do not need to add third-party jar packages to support pull.
/*** Use pull to parse XML documents * @ param inStream * @ return * @ throws Throwable */public static List
GetPersons (InputStream inStream) throws Throwable {List
Persons = null; Person person = null; XmlPullParser parser = Xml. newPullParser (); parser. setInput (inStream, "UTF-8"); int eventType = parser. getEventType (); // generates the first event while (eventType! = XmlPullParser. END_DOCUMENT) {// as long as it is not a document end event switch (eventType) {case XmlPullParser. START_DOCUMENT: // determine whether the current event is a document start event persons = new ArrayList
(); // Initialize the Person set break; case XmlPullParser. START_TAG: // determine whether the current event is a Tag Element start event String name = parser. getName (); // get the name of the element currently pointed to by the parser if ("person ". equals (name) {person = new Person (); // obtain the property value of the corresponding tag person. setId (new Integer (parser. getAttributeValue (0);} if (person! = Null) {if ("name ". equals (name) {// gets the value of person that the parser currently points to the next text node of the element. setName (parser. nextText ();} if ("age ". equals (name) {person. setAge (new Short (parser. nextText () ;}} break; case XmlPullParser. END_TAG: // determine whether the current event is a Tag Element end event if ("person ". equals (parser. getName () {persons. add (person); person = null;} break;} // enter the next element and trigger the event eventType = parser. next ();} return persons ;}
Use the pull parser to create an xml document:
/*** Use the pull parser to create an xml document * @ param persons * @ param writer * @ throws Throwable */public static void save (List
Persons, Writer writer) throws Throwable {XmlSerializer serializer = Xml. newSerializer (); serializer. setOutput (writer); serializer. startDocument ("UTF-8", true); serializer. startTag (null, "persons"); for (Person person: persons) {serializer. startTag (null, "person"); serializer. attribute (null, "id", person. getId (). toString (); serializer. startTag (null, "name"); serializer. text (person. getName (); serializer. endTag (null, "name"); serializer. startTag (null, "age"); serializer. text (person. getAge (). toString (); serializer. endTag (null, "age"); serializer. endTag (null, "person");} serializer. endTag (null, "persons"); serializer. endDocument (); writer. flush (); writer. close ();}
In the android project, use Junit to test the Methods:
Note that when using junit, you must add the following content to AndroidMainifest. xml:
Compile our java test class:
public class PersonServiceTest extends AndroidTestCase {private static final String TAG = "PersonServiceTest";public void testSAXGetPersons() throws Throwable{SAXPersonService service = new SAXPersonService();InputStream inStream = getClass().getClassLoader().getResourceAsStream("person.xml");List
persons = service.getPersons(inStream);for(Person person : persons){Log.i(TAG, person.toString()); }}public void testDomGetPersons() throws Throwable{InputStream inStream = getClass().getClassLoader().getResourceAsStream("person.xml");List
persons = DOMPersonService.getPersons(inStream);for(Person person : persons){Log.i(TAG, person.toString());}}public void testPullGetPersons() throws Throwable{InputStream inStream = getClass().getClassLoader().getResourceAsStream("person.xml");List
persons = PULLPersonService.getPersons(inStream);for(Person person : persons){Log.i(TAG, person.toString());}}}
Run the output to get the desired result!
Comparison of several methods:
SAX: reading a row and a row is highly efficient. It does not perform any further operations after reading the required data. It is complex and suitable for mobile devices.
DOM: The operation is simple. loading a DOM tree at the beginning affects the efficiency and speed when the XML file is relatively large.
* 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 the resolution in the program to stop where it is to be parsed.
In fact, pull parsing xml is not only applicable to android, but also can be used to parse xml files in our javase, but the corresponding jar package needs to be imported:
Kxml2-2.3.0.jar,: http://kxml.sourceforge.net/
Xmlpull_rj1_3_4c.jar: http://www.xmlpull.org/
In the past, we also used DOM4J and JDOM to parse xml. For more information, see my blog. However, we need to import corresponding jar packages:
DOM4J parsing XML: http://blog.csdn.net/harderxin/article/details/7285770
JDOM parsing XML: http://blog.csdn.net/harderxin/article/details/7285754