On the Android platform, you can use SAX (Simple API for XML) , Document Object Model (DOM) and the Pull parser that comes with Android to parse XML files .
DOM parsing: It degrades dramatically when dealing with large files. This problem is caused by the tree structure of the DOM, which takes up a lot of memory, and the DOM must load the entire document into memory before parsing the file, which is suitable for random access to XML
Parsing process:
1. Get the factory
DocumentBuilderFactory builderFactory =DocumentBuilderFactory.newInstance();
2. Get the builder
builder =builderFactory.newDocumentBuilder();
3. Parse into a Document object
Document document = builder.parse(xmlFile);
4. Get the root element
Element root = document.getDocumentElement();
5. Get the child nodes under the root element
NodeList childNodes =root.getChildNodes();
SAX parsing: Unlike DOM, SAX is an event-driven way of parsing XML. It reads XML files sequentially and doesn't need to load the entire file all at once. When encountering things like the beginning of the file, the end of the document, or the beginning of a tag and the end of a tag, it fires an event, and the user processes the XML file by writing processing code in its callback event, suitable for sequential access to XML.
1. Get the factory
SAXParserFactory factory =SAXParserFactory.newInstance();
2. Get Parser
SAXParser parser =factory.newSAXParser();
3. Start parsing
parser.parser(xmlFile, newMySAXListener());
PULL parsing: In addition to parsing XML files using SAX and DOM, you can also use Android's built-in Pull parser to parse XML files. The Pull parser operates similarly to the SAX parser. It provides similar events, such as: start element and end element events, use parser.next() to go to the next element and trigger the corresponding event. Events will be sent as numeric codes, so a switch can be used to handle events of interest. When the element starts parsing, call the parser.nextText() method to get the value of the next element of type Text.
1. Get the parser
XmlPullParserparser = Xml.newPullParser();
2. Set the input
parser.setInput(instream, “UTF-8”);
3. Get event type
int eventType = parser.getEventType();
4. Start parsing