Easy Tutorial
❮ Verilog Number Android Tutorial Animation ❯

7.2.1 Android XML Data Parsing

Category Android Basic Tutorial

Introduction:

>

In the previous two sections, we covered Android's built-in HTTP request methods: HttpURLConnection and HttpClient. Initially, I thought OkHttp was integrated, and I planned to explain its basic usage. However, I later found out that it requires a third-party library, so I decided to postpone it to the advanced section. In this section, we will learn about the three XML parsing methods provided by Android: SAX, DOM, and PULL. Let's dive into them!


1. XML Data Essentials

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


2. Comparison of Three XML Parsing Methods


3. SAX Parsing 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;
    // Current element tag
    private String tagName = null;

    /**
     * Triggered when the document start is read, commonly used for initialization
     */
    @Override
    public void startDocument() throws SAXException {
        this.persons = new ArrayList<Person>();
        Log.i("SAX", "Document header read, starting XML parsing");
    }

    /**
     * Called when a start tag is read, the second parameter is the tag name, 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", "Starting to process person element~");
        }
        this.tagName = localName;
    }

    /**
     * Reads content, the first parameter is the string content, followed by the start position and length
     */
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        // Check if the current tag is valid
        if (this.tagName != null) {
            String data = new String(ch, start, length);
            // Read the content of the tag
            if (this.tagName.equals("name")) {
                this.person.setName(data);
                Log.i("SAX", "Processing name element content");
            } else if (this.tagName.equals("age")) {
                this.person.setAge(Integer.parseInt(data));
                Log.i("SAX", "Processing age element content");
            }
        }
    }

    /**
     * Triggered when an element ends, here the object is added to the collection
     */
    @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", "Processing person element end~");
        }
        this.tagName = null;
    }

    /**
     * Triggered when the document end is read,
     */
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        Log.i("SAX", "Document footer read, XML parsing finished");
    }

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

Then, in MainActivity.java, write a method like this, and call it when you need to parse the XML:

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

Additional Notes:

Oh, I almost forgot to mention that we define the following person1.xml file and place it in the assets directory! The file content is as follows: person1.xml

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

We combine all three parsing methods into one demo, so we will post the complete effect diagram at the end. Here, let's post the printed Log, which will help you understand the SAX parsing process for XML more clearly:


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 DOM parser factory instance:
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            // ② Get DOM parser from Dom factory
            DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
            // ③ Read the XML file into the DOM parser
            Document doc = dbBuilder.parse(context.getAssets().open("person2.xml"));
            System.out.println("DomImplementation object handling this document=" + doc.getImplementation());
            // ④ Get the node list of elements named person in the document
            NodeList nList = doc.getElementsByTagName("person");
            // ⑤ Iterate through the collection, displaying the name of the elements and their child 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 person
                NodeList childNoList = personElement.getChildNodes();
                for (int j = 0; j < childNoList.getLength(); j++) {
                    Node childNode = childNoList.item(j);
                    // Check if the child note 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;
    }
}
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, which involves reading the entire file into a DOM parser, forming a tree, and then traversing the node list to retrieve the data we need!


5. PULL Parsing XML Data

-8.1.2 Summary of 13 Drawable Types in Android Part 2

-8.1.3 Summary of 13 Drawable Types in Android Part 3

-8.2.1 Comprehensive Analysis of Bitmap (Bitmaps) Part 1

-8.2.2 OOM Issues Caused by Bitmap

-8.3.1 Detailed Explanation of Three Drawing Tool Classes

-8.3.2 Practical Examples of Drawing Classes

-8.3.3 Paint API — MaskFilter (Mask)

-8.3.4 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 1)

-8.3.5 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 2)

-8.3.6 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 3)

-8.3.7 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 4)

-8.3.8 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 5)

-8.3.9 Paint API — ColorFilter (Color Filter) (1/3)

-8.3.10 Paint API — ColorFilter (Color Filter) (2/3)

-8.3.11 Paint API — ColorFilter (Color Filter) (3/3)

-8.3.12 Paint API — PathEffect (Path Effect)

-8.3.13 Paint API — Shader (Image Rendering)

-8.3.14 Paint Enumerations/Constants and ShadowLayer Shadow Effect

-8.3.15 Paint API — Typeface (Font Style)

-8.3.16 Canvas API Detailed Explanation (Part 1)

-8.3.17 Canvas API Detailed Explanation (Part 2) Clipping Methods Collection

-8.3.18 Canvas API Detailed Explanation (Part 3) Matrix and drawBitmapMesh

-8.4.1 Frame Animation Collection in Android

-8.4.2 Tween Animation Collection in Android

-8.4.3 Property Animation in Android - Introduction

-8.4.4 Property Animation in Android - Further Insights

-9.1 Playing Sound Effects with SoundPool (Duang~)

-9.2 Playing Audio and Video with MediaPlayer

-9.3 Using Camera to Take Photos

-9.4 Using MediaRecord to Record Audio

-10.1 TelephonyManager (Phone Manager)

-10.2 SmsManager (SMS Manager)

-10.3 AudioManager (Audio Manager)

-10.4 Vibrator (Vibrator)

-10.5 AlarmManager (Alarm Service)

-10.6 PowerManager (Power Service)

-10.7 WindowManager (Window Management Service)

-10.8 LayoutInflater (Layout Service)

-10.9 WallpaperManager (Wallpaper Manager)

-10.10 Sensor Topics (1) — Introduction

-10.11 Sensor Topics (2) — Orientation Sensor

-10.12 Sensor Topics (3) — Accelerometer/Gyroscope Sensor

-10.12 Sensor Topics (4) — Understanding Other Sensors

-10.14 Introduction to Android GPS

-11.0《2015 Latest Android Basic Beginner's Tutorial》Completion Celebration~

-12.1 Android Practice: DrySister Viewing Girls App (First Edition) — Project Setup and Simple Implementation

-12.2 DrySister Viewing Girls App (First Edition) — 2. Parsing Backend Data

-12.3 DrySister Viewing Girls App (First Edition) — 3. Image Loading Optimization (Writing a Small Image Cache Framework)

-12.4 DrySister Viewing Girls App (First Edition) — 4. Adding Data Caching (Introducing SQLite)

-12.5 DrySister Viewing Girls App (First Edition) — 5. Code Review, Adjustment, and Logging Class Writing

-12.6 DrySister Viewing Girls App (First Edition) — 6. Icon Creation, Obfuscation, Signing, Packaging, APK Slimming, App Release

WeChat Subscription

❮ Verilog Number Android Tutorial Animation ❯