Android: Dom parsing XML

Source: Internet
Author: User

Android: Dom parsing XML

Unlike the parsing of SAX and PULL, Dom parsing loads all XML files and assembles them into a Dom tree. Then, XML files are parsed through the relationship between nodes and nodes, occupying a large amount of memory, it is generally recommended to use SAX and PULL for parsing. Use the same example as above for analysis.

First, define an XML file: Student. xml. Note that the file is created instead of xml.

   
       
            
   
    
Zhang San
             
   
    
Male
   18      
        
            
   
    
Li Si
             
   
    
Female
   19      
        
            
   
    
Wang Wu
             
   
    
Male
   20      
    
   
Create a student class

package com.example.xml_sax_demo_1;public class Student {private int id;private String name;private int age;private String sex;public Student() {// TODO Auto-generated constructor stub}public int getId() {return id;}public Student(int id, String name, int age) {super();this.id = id;this.name = name;this.age = age;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + ",sex=" + sex+ ", age=" + age + "]";}}
Finally, a Button is used in the activity to parse the data, which uses several classes.

Package com. example. xml_sax_demo_1; 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; // note that the packages used are org. w3c. dom. * import org. w3c. dom. element; import org. w3c. dom. node; import org. w3c. dom. nodeList; import android. OS. bundle; import android. support. v7.app. actionBarActivity; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class MainActivity extends ActionBarActivity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Button button = (Button) findViewById (R. id. button); button. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View arg0) {// TODO Auto-generated method stubtry {readXML ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace () ;}});} private void readXML () throws Exception {List
 
  
List = new ArrayList
  
   
(); InputStream stream = this. getClass (). getClassLoader (). getResourceAsStream ("Student. xml "); // obtain the input stream DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance (); // DocumentBuilder builder = factory step by step. newDocumentBuilder (); Document document = builder. parse (stream); Element element = document. getDocumentElement (); // instantiate the element NodeList nodeList = element. getElementsByTagName ("student"); // obtain the node list for (int I = 0; I <nodeList. getLength (); I ++) {Element studentElement = (Element) nodeList. item (I); // corresponding to the list obtained above Student student = new Student (); // each node instantiates a student element student. setId (Integer. parseInt (studentElement. getAttribute ("id"); // get the attribute NodeList childNodeList = studentElement. getChildNodes (); // obtain the subnode list for (int j = 0; j <childNodeList. getLength (); j ++) {// if (childNodeList. item (j ). getNodeType () = Node. ELEMENT_NODE) // {if (childNodeList. item (j ). getNodeName (). equals ("name") {// If the subnode name is name student. setName (childNodeList. item (j ). getFirstChild () // store text data. getNodeValue ();} else if (childNodeList. item (j ). getNodeName (). equals ("sex") {student. setSex (childNodeList. item (j ). getFirstChild (). getNodeValue ();} else if (childNodeList. item (j ). getNodeName (). equals ("age") {student. setAge (Integer. parseInt (childNodeList. item (j ). getFirstChild (). getNodeValue ();} //} list. add (student); // add a student object to the list} for (Student stu: list) {System. out. println (stu. toString ());}}}
  
 
Result


Conclusion: The Code shows that Dom parsing loads all XML files, assembles them into a Dom tree, And parses XML files through the relationship between nodes and nodes, it is usually a continuous loop traversal, occupying a large amount of memory.

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.