Android XML data parsing

Introduction to this section:

In the previous two sections, we used Android’s built-in Http request methods: HttpURLConnection and HttpClient. We thought that OkHttp had been integrated, and then wanted to explain the basic usage of Okhttp. Later, we found that we still need to guide third parties. Forget it, let’s put it in the advanced part. , and in this section we will learn three solutions for parsing XML data provided by Android! They are: SAX, DOM, PULL three analysis methods, let's learn about them below!


1. Introduction to the key points of XML data

First, let's take a look at some requirements and concepts of XML data:


2. Comparison of three methods of parsing XML


3. SAX parses XML data

Core code :

SAX parsing class: SaxHelper.java :

/**
 * Created by Jay on 2015/9/8 0008.
 */
public class SaxHelper extends DefaultHandler {
    private Person person;
    private ArrayList<Person> persons;
    // currently parsed element tag
    private String tagName = null;

    /**
     * Triggered when the document start flag is read, usually some initialization operations are done here
     */
    @Override
    public void startDocument() throws SAXException {
        this.persons = new ArrayList<Person>();
        Log.i("SAX", "read to the document header, start parsing xml");
    }


    /**
     * Called when a start tag is read, the second parameter is the tag name, and the last parameter is the attribute array
     */
    @Override
    public void startElement(String uri, String localName, String qName,
                             Attributes attributes) throws SAXException {
        if (localName.equals("person")) {
            person = new Person();
            person.setId(Integer.parseInt(attributes.getValue("id")));
            Log.i("SAX", "Start processing the person element~");
        }
        this.tagName = localName;
    }


    /**
     * When the content is read, the first parameter is the string content, followed by the starting position and length
     */

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        / / Determine whether the current label is valid
        if (this.tagName != null) {
            String data = new String(ch, start, length);
            // read the content of the label
            if (this.tagName.equals("name")) {
                this.person.setName(data);
                Log.i("SAX", "Process name element content");
            } else if (this.tagName.equals("age")) {
                this.person.setAge(Integer.parseInt(data));
                Log.i("SAX", "Process age element content");
            }

        }

    }

    /**
     * Triggered when the processing element ends, here the object is added to the combination
     */
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (localName.equals("person")) {
            this.persons.add(person);
            person = null;
            Log.i("SAX", "end of processing person element~");
        }
        this.tagName = null;
    }

    /**
     * Triggered when the end of the document is read,
     */
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        Log.i("SAX", "read to the end of the document, xml parsing ends");
    }

    //Get the persons collection
    public ArrayList<Person> getPersons() {
        return persons;
    }

}

Then we write such a method in MainActivity.java, and then call it when we want to parse XML~

private ArrayList<Person> readxmlForSAX() throws Exception {
    //Get the file resource and create the input stream object
    InputStream is = getAssets().open("person1.xml");
    //①Create XML parsing processor
    SaxHelper ss = new SaxHelper();
    //②Get the SAX parsing factory
    SAXParserFactory factory = SAXParserFactory.newInstance();
    //③Create a SAX parser
    SAXParser parser = factory.newSAXParser();
    //④ Assign the xml parsing processor to the parser, parse the document, and send the event to the processor
    parser.parse(is, ss);
    is.close();
    return ss.getPersons();
}

Some other words :

Well, by the way, I forgot to tell you that we defined the following person1.xml file and put it in the assets directory! The content of the file is as follows: person1.xml

<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id = "11">
        <name>SAX解析</name>
        <age>18</age>
    </person>
    <person id = "13">
        <name>XML1</name>
        <age>43</age>
    </person>
</persons>

We combined the three parsing methods into one demo, so we posted all the renderings at the end. Here, post the printed Log. I believe everyone will understand the SAX parsing XML process more clearly:

In addition, the blank text outside is also a text node! These nodes will also be taken during parsing!


4. DOM parsing XML data

Core code :

DomHelper.java

/**
 * Created by Jay on 2015/9/8 0008.
 */
public class DomHelper {
    public static ArrayList<Person> queryXML(Context context)
    {
        ArrayList<Person> Persons = new ArrayList<Person>();
        try {
            //①Get the factory example of the DOM parser:
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            //② Get the dom parser from the Dom factory
            DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
            //③ Read the xml file to be parsed into the Dom parser
            Document doc = dbBuilder.parse(context.getAssets().open("person2.xml"));
            System.out.println("Process the DomImplemention object of this document=" + doc.getImplementation());
            //④ Get the node list of the element named person in the document
            NodeList nList = doc.getElementsByTagName("person");
            //⑤ traverse the collection, display the elements in the collection and the names of sub-elements
            for(int i = 0;i < nList.getLength();i++)
            {
                //Start parsing from the Person element
                Element personElement = (Element) nList.item(i);
                Person p = new Person();
                p.setId(Integer.valueOf(personElement.getAttribute("id")));

                //Get the Note collection of name and age under the person
                NodeList childNoList = personElement.getChildNodes();
                for(int j = 0;j < childNoList.getLength();j++)
                {
                    Node childNode = childNoList.item(j);
                    //Determine whether the subnote type is an element Note
                    if(childNode.getNodeType() == Node.ELEMENT_NODE)
                    {
                        Element childElement = (Element) childNode;
                        if("name".equals(childElement.getNodeName()))
                            p.setName(childElement.getFirstChild().getNodeValue());
                        else if("age".equals(childElement.getNodeName()))
                            p.setAge(Integer.valueOf(childElement.getFirstChild().getNodeValue()));
                    }
                }
                Persons.add(p);
            }
        } catch (Exception e) {e.printStackTrace();}
        return Persons;
    }
}

Code analysis :

From the code, we can see the process of DOM parsing XML. First, the entire file is read into the Dom parser, and then a tree is formed. Then we can traverse the node list to obtain the data we need!


5. PULL parses XML data

Process of parsing XML data using PULL :

Core code :

public static ArrayList<Person> getPersons(InputStream xml)throws Exception
{
    //XmlPullParserFactory pullPaser = XmlPullParserFactory.newInstance();
    ArrayList<Person> persons = null;
    Person person = null;
    // Create a factory for xml parsing  
    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  
    // Get a reference to the xml parsing class  
    XmlPullParser parser = factory.newPullParser();  
    parser.setInput(xml, "UTF-8");  
    // Get the type of event  
    int eventType = parser.getEventType();  
    while (eventType != XmlPullParser.END_DOCUMENT) {  
        switch (eventType) {  
        case XmlPullParser.START_DOCUMENT:  
            persons = new ArrayList<Person>();  
            break;  
        case XmlPullParser.START_TAG:  
            if ("person".equals(parser.getName())) {  
                person = new Person();  
                // get attribute value  
                int id = Integer.parseInt(parser.getAttributeValue(0));  
                person.setId(id);  
            } else if ("name".equals(parser.getName())) {  
                String name = parser.nextText();// Get the content of this node  
                person.setName(name);  
            } else if ("age".equals(parser.getName())) {  
                int age = Integer.parseInt(parser.nextText());  
                person.setAge(age);  
            }  
            break;  
        case XmlPullParser.END_TAG:  
            if ("person".equals(parser.getName())) {  
                persons.add(person);  
                person = null;  
            }  
            break;  
        }  
        eventType = parser.next();  
    }  
    return persons;  
}  

The process of using Pull to generate xml data :

Core code :

public static void save(List<Person> persons, OutputStream out) throws Exception {
    XmlSerializer serializer = Xml.newSerializer();
    serializer.setOutput(out, "UTF-8");
    serializer.startDocument("UTF-8", true);
    serializer.startTag(null, "persons");
    for (Person p : persons) {
        serializer.startTag(null, "person");
        serializer.attribute(null, "id", p.getId() + "");
        serializer.startTag(null, "name");
        serializer.text(p.getName());
        serializer.endTag(null, "name");
        serializer.startTag(null, "age");
        serializer.text(p.getAge() + "");
        serializer.endTag(null, "age");
        serializer.endTag(null, "person");
    }

    serializer.endTag(null, "persons");
    serializer.endDocument();
    out.flush();
    out.close();
}

6. Code sample download:

Running effect diagram :

Guess you like

Origin blog.csdn.net/leyang0910/article/details/131473244