Android application using DOM method to parse XML format data

  • 2021-06-29 12:05:27
  • OfStack

DOM is easier to master than SAX because it does not involve callbacks and complex state management. However, the implementation of DOM often keeps all XML nodes in memory, which makes processing larger documents less efficient.
XML Basic Node Type
node - DOM Basic Data Type
Element - The primary object to process is Element
Attr - Attributes of the element
Text - Actual content of an Element or Attr
Document - Represents the entire XML document, and an Document object is often referred to as an DOM tree

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


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

2. Create a new Person object to store 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; 
  } 
   
} 

3Create a new DomPersonService.class, comment I write clearly, you 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.xml Input stream of file  
    InputStream is = MainActivity.class.getClassLoader().getResourceAsStream("android.xml"); 
    List<Person> persons = new ArrayList<Person>(); 
     
    // instantiation DocumentBuilderFactory and DocumentBuilder And create Document 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = factory.newDocumentBuilder(); 
    Document document = builder.parse(is); 
     
    // Return to the root of the document (root) element  
    Element rootElement = document.getDocumentElement(); 
     
    // Obtain 1 individual Note(DOM Basic data types ) Collection, here are two person Note 
    NodeList nodes = rootElement.getElementsByTagName("person"); 
     
    // ergodic Note aggregate  
    for(int i=0; i<nodes.getLength(); i++){ 
      // First from 1 individual person Element begins parsing  
      Element personElement = (Element) nodes.item(i); 
      Person person = new Person(); 
      person.setId(Integer.valueOf(personElement.getAttribute("id"))); 
       
      // Obtain person Below name  and  age  Of Note aggregate  
      NodeList chileNodes = personElement.getChildNodes(); 
      for(int y=0; y<chileNodes.getLength(); y++){ 
        Node childNode = chileNodes.item(y); 
         
        // Judger Note The type of is 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.getFirstChild().getNodeValue())); 
        } 
        } 
      } 
       
      Log.e("log", person.toString()); 
       
      persons.add(person); 
    } 
     
    return persons; 
     
  } 
} 

As for DOM parsing XML, we need to know the relationship between the nodes in order to operate the object tree better. It is worth noting that when building Element, we should pay attention to the import of jar package and choose org.w3c.dom.Element instead of other packages.

PS:DOM parsing, although not recommended in android, does not mean it is impossible to implement.The principle of dom is to treat all parts of the xml file as nodes, and all nodes end up with a node tree due to hierarchical relationships.DOM parses the tree in memory and allows the user to perform related operations.

Here are a few commonly used methods in dom:

Common methods of the Node interface

1 node can be called
short getNodeType()
The method returns a constant representing the 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 an NodeList object consisting of all the child nodes of the current node.Node Call
Node getFirstChild()
Returns the first child node of the current node.Node Call
Node getLastChild()
Returns the last child of the current node.Node can call
NodeList getTextContent()
Returns the text content in the current node and all descendant nodes.

There are many other ways we can learn more about api.Since the main purpose here is to learn android, a little bit about dom is enough.


Related articles: