Summary of 3 Ways of Parsing xml File in Android

  • 2021-08-21 21:17:58
  • OfStack

Preface

xml is a data transmission format, Android layout files, settings files are used to represent it. There are also many ways to parse xml files in Android. Here are three commonly used ways: Dom, SAX and dom4j. The following words are not much to say, let's take a look at the detailed introduction.

Look at a simple xml file first:


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
 < Books   Publishing house =" Horse ">
 < Book title > How to succeed </ Book title >
 < Author >uniapp</ Author >
 < Selling price >666</ Selling price >
 </ Books >
 < Books >
 < Book title > How to succeed 1</ Book title >
 < Author >uniapp</ Author >
 < Selling price >1991</ Selling price >
 </ Books >
</ Bookshelf >

1. Dom parsing mode

Dom parsing reads the whole xml file into memory once through Document class, and then realizes the addition, deletion and modification of elements in xml file by operating the attributes of Document instance. The specific code is as follows:

2 SAX Analysis

SAX to xml file read while parsing the way, just like we read the article with our eyes, one line and one line. Compared with the instantaneous memory peak generated by Dom, SAX consumes more stable memory. It provides external interface through parsing class, and implements:


public class SaxDemo {
 @Test
 public void main() throws ParserConfigurationException, SAXException, IOException{
 // Factory class instance 
 SAXParserFactory fac = SAXParserFactory.newInstance();
 // Create a parser 
 SAXParser parser = fac.newSAXParser();
 // Parse a document 
 XMLReader reader = parser.getXMLReader();
 reader.setContentHandler(new MyDefultHandle());
 reader.parse("./app/src/main/java/test/DTD.xml");

 }
}

class MyDefultHandle extends DefaultHandler{

 @Override
 public void startDocument() throws SAXException {
 super.startDocument();

 System.out.println(" Document start ");
 }

 @Override
 public void endDocument() throws SAXException {
 super.endDocument();
 System.out.println(" End of document ");
 }

 private boolean isPrice = false;
 @Override
 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
 super.startElement(uri, localName, qName, attributes);
 System.out.println(" Element start : " + qName);

 }

 @Override
 public void endElement(String uri, String localName, String qName) throws SAXException {
 super.endElement(uri, localName, qName);

 if (" Selling price ".equals(qName)){
  isPrice = false;
 }
 System.out.println(" End of element : " + qName);

 }

 @Override
 public void characters(char[] ch, int start, int length) throws SAXException {
 super.characters(ch, start, length);
 if (isPrice){
  System.out.println(" Content : " + new String(ch, start, length));
 }
 }
}

Analysis of 3 Dom4j

Dom4j parsing is a parsing method given by the third open source library, which combines the advantages of Dom and SAX, reads xml files into memory step by step, and can access nodes in an object-oriented way. The code is as follows:


/**
 *  Read property values 
 * */
 public void readAttr() throws DocumentException {
 Document doc = getDocument();
 List<Element> list = doc.getRootElement().elements(" Books ");
 for (int i = 0; i < list.size(); i++) {
  Element el = (Element) list.get(i);
  Attribute att = el.attribute(" Publishing house ");
  System.out.print(" Results : " + att.getName() + att.getValue());
 }
 }

 /**
 *  Read node 
 * */
 public void read() throws DocumentException {
 /**
  *  You can't get a value beyond the level 
  * */
 Document doc = getDocument();
 org.dom4j.Element el = doc.getRootElement();
 Element firstEl = el.element(" Books ");
 Element firstBookEl = firstEl.element(" Book title ");

 String name = firstBookEl.getText();
 System.out.println(" Book title : " + name);
 }

 public void update() throws DocumentException, IOException {
 Document doc = getDocument();
 List<Element> list = doc.getRootElement().elements(" Books ");
 Element element = list.get(0);
 Element priceEl = element.element(" Selling price ");
 priceEl.setText("888 Yuan ");
 XMLWriter writer = new XMLWriter(new FileOutputStream("./app/src/main/java/test/Dom4j3.xml"));
 writer.write(doc);
 }

 /**
 *  Delete Node 
 * */
 public void deletePrice() throws Exception{
 SAXReader reader = new SAXReader();
 Document doc = reader.read("./app/src/main/java/test/Dom4j1.xml");
 Element el = (Element) doc.getRootElement().elements(" Books ").get(1);
 Element elPrice = (Element) el.elements(" Selling price ").get(1);
 elPrice.getParent().remove(elPrice);
 XMLWriter writer = new XMLWriter(new FileOutputStream("./app/src/main/java/test/Dom4j2.xml"));
 writer.write(doc);
 writer.close();
 }
 /**
 *  Add nodes 
 * */
 public void addEl() throws DocumentException, IOException {
 Document doc = getDocument();
 Element el = (Element) doc.getRootElement().elements(" Books ").get(1);
 el.addElement(" Selling price ").setText("6.66 Yuan ");
 XMLWriter writer = new XMLWriter(new FileOutputStream("./app/src/main/java/test/Dom4j1.xml"));
 writer.write(doc);
 writer.close();
 }

 private Document getDocument() throws DocumentException {
 SAXReader reader = new SAXReader();
 return reader.read("./app/src/main/java/test/DTD.xml");
 }

Combining the characteristics of the above three parsing methods, we can draw a conclusion: if the xml file is very small, we can choose the object-oriented Dom or dom4j; On the contrary, SAX mode can be selected, and the lack of actual memory on one side causes flashback.

Summarize


Related articles: