SoFunction
Updated on 2025-04-14

Steps to parse XML format data using SAX on Android

1. Overview

SAX (Simple API for XML) is an event-driven XML parsing method suitable for handling large-scale XML documents. The SAX parser does not load the entire XML into memory, but parses it line by line, so inBetter than DOM parsing in performance and memory usage

2. Applicable scenarios

  • Handle large XML files(such as RSS subscriptions, log files)
  • Streaming analysis(Save memory)
  • Just read the data(No need to modify the XML structure)

3. XML example

Assume that there is the following XML data

<?xml version="1.0" encoding="UTF-8"?>
<apps>
    <app >
        <name>MyApp</name>
        <version>1.0.0</version>
    </app>
    <app >
        <name>AnotherApp</name>
        <version>2.3.4</version>
    </app>
</apps>

4. SAX parsing steps

4.1 Create ContentHandler to process XML

SAX analysis is based onContentHandlerHandle XML parsing events.

import 
import 
import 
​
class AppContentHandler : DefaultHandler() {
    private var nodeName = ""
    private lateinit var id: StringBuilder
    private lateinit var name: StringBuilder
    private lateinit var version: StringBuilder
​
    override fun startDocument() {
        id = StringBuilder()
        name = StringBuilder()
        version = StringBuilder()
    }
​
    override fun startElement(uri: String?, localName: String?, qName: String?, attributes: Attributes?) {
        nodeName = localName ?: ""
        if (localName == "app" && attributes != null) {
            ("AppContentHandler", "App ID: ${("id")}")
        }
    }
​
    override fun characters(ch: CharArray?, start: Int, length: Int) {
        when (nodeName) {
            "name" -> (ch, start, length)
            "version" -> (ch, start, length)
        }
    }
​
    override fun endElement(uri: String?, localName: String?, qName: String?) {
        if (localName == "app") {
            ("AppContentHandler", "App Name: ${().trim()}")
            ("AppContentHandler", "App Version: ${().trim()}")
            (0)
            (0)
        }
    }
}

4.2 Use SAX to parse XML in Activity or Service

import 
import 
import 
​
fun parseXml(xmlData: String) {
    val factory = ()
    val parser = ()
    val xmlReader = 
     = AppContentHandler()
    (InputSource(StringReader(xmlData)))
}

4.3 Calling parsing functions

val xmlData = """
<apps>
    <app >
        <name>MyApp</name>
        <version>1.0.0</version>
    </app>
    <app >
        <name>AnotherApp</name>
        <version>2.3.4</version>
    </app>
</apps>
""".trimIndent()
​
parseXml(xmlData)

5. Analysis process

  • startDocument()Initialize the variable.
  • startElement()ReadTag nameandproperty
  • characters()ReadText in tags
  • endElement()deal withData storage and output

6. Advantages and limitations

advantage

Low memory footprint(Fit for large XML files) ✔Fast parsing speed(Based on streaming) ✔Official recommendation(Built-in Android support)

shortcoming

Random access is not supported(Only parsed in sequence) ✘Not suitable for modifying XML structures(Applicable to reading data only)

7. Applicable scenarios

  • parse XML returned by network requests
  • Process RSS subscription data
  • Parse configuration files(like

8. Conclusion

SAX parsing is a kind ofEfficient and lightweightThe XML processing method is suitable for Android development, especially when parsing large XML data.

This is the article about the operation steps of Android using SAX to parse XML format data. For more related content for Android SAX parsing XML data, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!