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
- 2.3.6 ToggleButton and Switch
- 2.3.7 ProgressBar (Progress Bar)
- 2.3.8 SeekBar (Drag Bar)
- 2.3.9 RatingBar (Star Rating Bar)
- 2.4.1 ScrollView (Scroll Bar)
- 2.4.2 Date & Time Components (Part 1)
- 2.4.3 Date & Time Components (Part 2)
- 2.4.4 Adapter Basics
- 2.4.5 Simple Usage of ListView
- 2.4.6 BaseAdapter Optimization
- 2.4.7 ListView Focus Issues
- 2.4.8 Solving Checkbox Misalignment in ListView
- 2.4.9 Data Update Issues in ListView
- 2.5.0 Building a Reusable Custom BaseAdapter
- 2.5.1 Implementing Multiple Item Layouts in ListView
- 2.5.2 Basic Usage of GridView (Grid View)
- 2.5.3 Basic Usage of Spinner (List Dropdown)
- 2.5.4 Basic Usage of AutoCompleteTextView (Auto-complete Text Field)
- 2.5.5 Basic Usage of ExpandableListView (Collapsible List)
- 2.5.6 Basic Usage of ViewFlipper (Flip View)
- 2.5.7 Basic Usage of Toast
- 2.5.8 Detailed Explanation of Notification (Status Bar Notification)
- 2.5.9 Detailed Explanation of AlertDialog (Dialog Box)
- 2.6.0 Basic Usage of Other Common Dialogs
- 2.6.1 Basic Usage of PopupWindow (Floating Box)
- 2.6.2 Menu (Menu)
- 2.6.3 Simple Usage of ViewPager
- 2.6.4 Simple Usage of DrawerLayout (Official Side Sliding Menu)
- 3.1.1 Event Handling Mechanism Based on Listeners
- 3.2 Event Handling Mechanism Based on Callbacks
- 3.3 Analysis of Handler Message Passing Mechanism
- 3.4 TouchListener vs OnTouchEvent + Multi-touch
- 3.5 Listening for Content Changes in EditText
- 3.6 Responding to System Setting Events (Configuration Class)
- 3.7 AsyncTask Asynchronous Tasks
- 3.8 Gestures (Gestures)
- 4.1.1 Introduction to Activity
- 4.1.2 Intermediate Activity
- 4.1.3 Advanced Activity
- 4.2.1 Introduction to Service
- 4.2.2 Advanced Service
- 4.2.3 Expert Service
- 4.3.1 Basic BroadcastReceiver
- 4.3.2 Advanced BroadcastReceiver
- 4.4.1 Introduction to ContentProvider
- 4.4.2 Advanced ContentProvider - Document Provider
- 4.5.1 Basic Usage of Intent
- 4.5.2 Passing Complex Data with Intent
- 5.1 Basic Overview of Fragment
- 5.2.1 Fragment Example - Bottom Navigation Bar Implementation (Method 1)
- 5.2.2 Fragment Example - Bottom Navigation Bar Implementation (Method 2)
- 5.2.3 Fragment Example - Bottom Navigation Bar Implementation (Method 3)
- 5.2.4 Fragment Example - Bottom Navigation Bar + ViewPager Page Sliding
- 5.2.5 Fragment Example - Simple Implementation of News/Shopping App List Fragment
- 6.1 Data Storage and Access - File Storage and Reading
- 6.2 Data Storage and Access - SharedPreferences for Saving User Preferences
- 6.3.1 Data Storage and Access - Introduction to SQLite Database
- 6.3.2 Data Storage and Access - Advanced SQLite Database
- 7.1.1 Android Network Programming and HTTP Protocol Learning
- 7.1.2 Android HTTP Request and Response Headers Learning
- 7.1.3 Android HTTP Request Method: HttpURLConnection
- 7.1.4 Android HTTP Request Method: HttpClient
- 7.2.1 Android XML Data Parsing
- 7.2.2 Android JSON Data Parsing
- 7.3.1 Android File Upload
- 7.3.2 Android File Download (1)
- 7.3.3 Android File Download (2)
- 7.4 Android Calling WebService
- 7.5.1 Basic Usage of WebView (Web View)
- 7.5.2 Basic Interaction Between WebView and JavaScript
- 7.5.3 WebView Considerations After Android 4.4
- 7.5.4 WebView File Download
- 7.5.5 WebView Cache Issues
- 7.5.6 WebView Handling Error Code Information from Web Pages
- 7.6.1 Socket Network Basics Preparation
- 7.6.2 TCP Protocol Based Socket Communication (1)
- 7.6.3 TCP Protocol Based Socket Communication (2)
- 7.6.4 UDP Protocol Based Socket Communication -8.1.1 Summary of 13 Drawable Types in Android Part 1
-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.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.2 DrySister Viewing Girls App (First Edition) — 2. Parsing Backend Data
-12.4 DrySister Viewing Girls App (First Edition) — 4. Adding Data Caching (Introducing SQLite)