Android DOM parsing XML and androiddomxml

Source: Internet
Author: User

Android DOM parsing XML and androiddomxml
1. Introduction to DOM Parsing

DOM is a collection of nodes or information fragments based on the tree structure. It allows developers to use DOM APIs to traverse the XML tree and retrieve the required data. To analyze this structure, you usually need to load the entire document and construct a tree structure before you can retrieve and update node information.

Android fully supports DOM parsing. DOM objects can be used to read, search, modify, add, and delete XML documents.

How DOM works: when using DOM to operate an XML file, you must first parse the file and divide the file into independent elements, tree trees, and annotations, then, the XML file is represented in the memory in the form of a node tree, you can access the document content through the node tree, and modify the document as needed-this is the working principle of DOM.

When DOM is implemented, a set of interfaces are defined for the parsing of the XML document. The parser reads the entire document and constructs a tree structure with resident memory so that the code can use the DOM interface to operate the entire tree structure.

Because the DOM is stored in the memory in a tree structure, the retrieval and update efficiency is higher. However, for a very large document, parsing and loading the entire document will consume a lot of resources. Of course, it is feasible to use DOM if the content of the XML document is small.

Basic XML node types:

Node --- basic DOM data type

Element --- the main object to be processed is Element

Attr --- attributes of Elements

Text --- the actual content of an Element or Attr

Document --- a Document that represents the entire XML Document. A Document object is also called a tree.

Advantage: the entire document is read into the memory, which is easy to operate and supports multiple functions such as modification, deletion, and re-arrangement.

Disadvantage: Read the entire document into the memory, leaving too many unnecessary nodes, wasting both memory and space.

Usage: Once a document is read, you need to perform operations on the document multiple times, and when the hardware resources are sufficient (memory, CPU ).

2. DOM parsing Step 1. Create a DocumentBuilderFactory instance using DocumentBuilderFactory.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
2. Use DocumentBuilderFactory to create DocumentBuilder.
DocumentBuilder builder = factory.newDocumentBuilder();
3. Load the XML document.
Document dom = builder.parse(inputStream);
4. Get the root node (Element) of the document)
 Element root = dom.getDocumentElement();
5. Obtain the list of all child nodes in the root node (NodeList)
 NodeList items = root.getElementsByTagName("person");
6. Then retrieve the nodes to be read from the subnode list.

 

// All subnodes
For (int I = 0; I <items. getLength (); I ++) {// get a Person node Element personNode = (Element) items. item (I); // obtain all subnodes under the Person node (blank nodes and name/age elements between labels) NodeList childNodes = personNode. getChildNodes ();
// Subnode for (int j = 0; j <childNodes. getLength (); j ++) {Node node = childNodes. item (j );
// Determine whether the Element type is if (node. getNodeType () = Node. ELEMENT_NODE) {Element childNode = (Element) node ;...}}}
Iii. DOM parsing XML Code 1. Create an XML file itcase. xml and put it in the res/raw folder.
<?xml version="1.0" encoding="UTF-8"?><persons>    <person id="23">        <name>liming</name>        <age>30</age>    </person>    <person id="20">        <name>lixiangmei</name>        <age>25</age>    </person></persons>

If there is no raw folder, create a raw folder under the res folder and create an xml file.

2. Modify the view
 <Button        android:id="@+id/dom_button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_marginTop="@dimen/fab_margin"        android:gravity="center_horizontal"        android:text="@string/DOM" /><TextView        android:id="@+id/text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World!" />
3. Add the AnalyzeDOM class
package com.zhangmiao.analyzexmldemo;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;/** * Created by zhangmiao on 2016/12/14. */public class AnalyzeDOM {    public static List<Person> readXML(InputStream inputStream) {        List<Person> persons = new ArrayList<>();        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        try {            DocumentBuilder builder = factory.newDocumentBuilder();            Document dom = builder.parse(inputStream);            Element root = dom.getDocumentElement();            NodeList items = root.getElementsByTagName("person");            for (int i = 0; i < items.getLength(); i++) {                Person person = new Person();                Element personNode = (Element) items.item(i);                person.setId(new Integer(personNode.getAttribute("id")));                NodeList childNodes = personNode.getChildNodes();                for (int j = 0; j < childNodes.getLength(); j++) {                    Node node = childNodes.item(j);                    if (node.getNodeType() == Node.ELEMENT_NODE) {                        Element childNode = (Element) node;                        if ("name".equals(childNode.getNodeName())) {                            person.setName(childNode.getFirstChild().getNodeValue());                        } else if ("age".equals(childNode.getNodeName())) {                            person.setAge(new Short(childNode.getFirstChild().getNodeValue()));                        }                    }                }                persons.add(person);            }            inputStream.close();        } catch (Exception e) {            e.printStackTrace();        }        return persons;    }}
4. Modify the MainActivity class
package com.zhangmiao.analyzexmldemo;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.util.Log;import android.view.View;import android.view.Menu;import android.view.MenuItem;import android.widget.Button;import android.widget.TextView;import org.xml.sax.InputSource;import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStreamWriter;import java.io.StringWriter;import java.util.List;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private static final String TAG = "AnalyzeXMLDemo";    private TextView mTextView;    private InputStream inputStream;    @Override    protected void onCreate(Bundle savedInstanceState) {        Log.v(TAG, "onCreate");        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);        fab.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)                        .setAction("Action", null).show();            }        });        Button domButton = (Button) findViewById(R.id.dom_button);        mTextView = (TextView) findViewById(R.id.text);        domButton.setOnClickListener(this);    }    @Override    public void onClick(View v) {        String result = "";        inputStream = getResources().openRawResource(R.raw.itcase);        switch (v.getId()) {case R.id.dom_button:                result += "--------- DOM ---------" + "\n";                if (inputStream == null) {                    result = "inputStream is null";                } else {                    List<Person> personList = AnalyzeDOM.readXML(inputStream);                    if (personList != null) {                        for (int i = 0; i < personList.size(); i++) {                            String message = "id = " + personList.get(i).getId() + " , name = " + personList.get(i).getName()                                    + " , age = " + personList.get(i).getAge() + ".\n";                            result += message;                        }                    }                }                mTextView.setText(result);                break;default:                break;        }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}

References:

Http://www.open-open.com/lib/view/open1392780226397.html

Http://www.cnblogs.com/weixing/archive/2013/08/07/3243366.html

Http://www.tuicool.com/articles/IvQvyq

 

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.