Basic methods for parsing XML format data using DOM in Android applications _android

Source: Internet
Author: User

Dom is easier to master than sax because she doesn't involve callbacks and complex state management, however, DOM implementations often keep all of the XML nodes in memory, making it inefficient to handle larger documents.
XML Basic Node type
Node-dom Basic data types
Element-The most important object to deal with IS element
Attr-Attributes of elements
Text-The actual content of an element or attr
Document-Represents the entire XML document, and a document object is often referred to as a DOM tree

1. Create a new android.xml in the SRC directory

<?xml version= "1.0" encoding= "UTF-8"?> 
<persons> 
  <person id= "A" > 
    <name> xiaanming</name> 
    <age>23</age> 
  </person> 
  <person id= "> 
    <" name>liudehua</name> 
    <age>28</age> 
  </person> 
</persons> 

2. Create a new Person object to store the parsed content

Package com.example.dom_parser; 
 
public class Person { 
  private int id; 
  private String name; 
  private int age; 
   
  Public person () {} public person 
   
  (int id, String name, int age) { 
    this.id = ID; 
    this.name = name; 
    This.age = age; 
  } 
 
  public int getId () {return 
    ID; 
  } 
 
  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; 
  } 
   
  @Override public 
  String toString () {return 
    "id =" + id + ", name =" + Name + ", age =" + age; 
  } 
   
} " 

3 Create a Dompersonservice.class, note I write clearly, everyone to see

Package com.example.dom_parser; 
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 Android.util.Log; public class Dompersonservice {public static list<person> ReadXML () throws throwable{//Get Android.x 
    ml file input stream InputStream is = MainActivity.class.getClassLoader (). getResourceAsStream ("Android.xml"); 
     
    list<person> persons = new arraylist<person> (); Instantiate Documentbuilderfactory and Documentbuilder, and create document Documentbuilderfactory factory = 
    Documentbuilderfactory.newinstance (); 
    Documentbuilder builder = Factory.newdocumentbuilder (); 
     
    Document document = Builder.parse (IS); 
     
    Returns the root (root) Element rootelement = Document.getdocumentelement () of the document; BeenTake a collection of note (DOM basic data type), here are two person Note nodelist nodes = rootelement.getelementsbytagname ("person"); Traverse the note collection for (int i=0; i<nodes.getlength (); i++) {//parse element personelement = (from first person element first) = (Elem 
      ENT) Nodes.item (i); 
      person who = new person (); 
       
      Person.setid (integer.valueof) (Personelement.getattribute ("id")); 
      Gets the note set nodelist Chilenodes = Personelement.getchildnodes () for name and age below person. 
         
        for (int y=0; y<chilenodes.getlength (); y++) {Node Childnode = Chilenodes.item (y);  To determine the type of the child note is the element Note if (childnode.getnodetype () = = Node.element_node) {element childelement = (Element) 
        Childnode; 
        if ("Name". Equals (Childelement.getnodename ())) {Person.setname (Childelement.getfirstchild (). Getnodevalue ()); }else if ("Age". Equals (Childelement.getnodename ())) {Person.setage (integer.valueof CHILDELEMENT.GETFIRSTC Hild (). Getnodevalue ())); 
       
      }} log.e ("Log", person.tostring ()); 
    Persons.add (person); 
     
  return persons; 
 } 
}

As for DOM parsing XML, we have to know the relationship between the nodes clearly in order to better operate the object tree, it is worth noting that when building Element, attention should be paid to the import of jar package, to select Org.w3c.dom.Element, instead of other packages.

Ps:dom parsing Although we are not recommended in Android, this does not mean that it cannot be implemented. The principle of DOM is to think of various parts of an XML file as nodes, and all nodes form a node tree at the end of the hierarchical relationship. The way DOM is parsed is to survive the tree in memory and allow the user to perform related operations.

Here are a few of the methods that are often used in the DOM:

Common methods of Node interface

A node can call
Short Getnodetype ()
method returns a constant that represents a node type (a constant value specified by the node interface), for example, for an element node, the value returned by the Getnodetype () method is:
Node.element_node
Node can call
NodeList Getchildnodes ()
Returns a NodeList object that consists of all the child nodes of the current node. Node calls
Node Getfirstchild ()
Returns the first child node of the current node. Node calls
Node Getlastchild ()
Returns the last child node of the current node. Node can call
NodeList Gettextcontent ()
Returns the text content in the current node and all descendants nodes.

There are many other ways that we can learn more through the API. Because this is primarily about learning about Android, it's OK to know a little about DOM.

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.