Android developed DOM method for parsing xml files
- 2020-12-09 01:00:44
- OfStack
This article gives an example of how DOM parses xml files in Android. To share for your reference, the details are as follows:
1. Write xml files in assets files
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="23">
<name> Li Ming </name>
<age>30</age>
</person>
<person id="20">
<name> Li Xiangmei </name>
<age>25</age>
</person>
</persons>
2. Write an DOM parse operation in service
package com.example.service;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.example.domain.Person;
public class XMLDomService {
public List<Person> parseXML(InputStream is) {
List<Person> list = new ArrayList<Person>();
// create DOM A factory object
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
// DocumentBuilder object
DocumentBuilder builder = factory.newDocumentBuilder();
// Get the document object
Document document = builder.parse(is);
// Gets the document object root
Element root = document.getDocumentElement();
// To obtain persons All of the root nodes person The node object
NodeList personNodes = root.getElementsByTagName("person");
// I'm going through all of them person node
for (int i = 0; i < personNodes.getLength(); i++) {
Person person = new Person();
// According to the item(index) Gets the node object corresponding to the index
Element personNode = (Element) personNodes.item(i); // specific person node
// Set up the id Attribute values
person.setId(Integer.parseInt(personNode.getAttribute("id")));
// Gets all the byte points below the node
NodeList personChildNodes = personNode.getChildNodes();
// traverse person The byte points
for (int index = 0; index < personChildNodes.getLength(); index++) {
// Get child nodes
Node node = personChildNodes.item(index);
// judge node Whether the node is an element node
if (node.getNodeType() == Node.ELEMENT_NODE) {
// Converts nodes into element nodes
Element element = (Element) node;
// Determine if the element node is name Element nodes
if ("name".equals(element.getNodeName())) {
person.setName(element.getFirstChild()
.getNodeValue());
} else if ("age".equals(element.getNodeName())) { // Judge whether or not age node
person.setAge(new Short(element.getFirstChild().getNodeValue()));
}
}
}
// the person Object is added to the collection
list.add(person);
}
// Close the input stream
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}
3. Display operations in Activity
package com.example.lession03_xml;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.example.domain.Person;
import com.example.service.XMLContentHandler;
import com.example.service.XMLDomService;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputBinding;
import android.widget.Button;
import android.widget.Toast;
public class XmlActivityextends Activity {
// Announcement component
public Button btn_sax,btn_dom,btn_pull;
public XMLDomService xmlDomService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the view to display
setContentView(R.layout.activity_xml);
xmlDomService=new XMLDomService();
// According to the id Access to the component
btn_sax=(Button) findViewById(R.id.btn_sax);
btn_dom=(Button) findViewById(R.id.btn_dom);
btn_pull=(Button) findViewById(R.id.btn_pull);
// Register the event for the button
btn_sax.setOnClickListener(new MyOnclickListener());
btn_dom.setOnClickListener(new MyOnclickListener());
btn_pull.setOnClickListener(new MyOnclickListener());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.xml, menu);
return true;
}
// An anonymous class
class MyOnclickListener implements OnClickListener{
@Override
public void onClick(View v) {
int id=v.getId();
switch (id) {
case R.id.btn_sax:
Toast.makeText(XmlActivity.this," using SAX parsing ", Toast.LENGTH_LONG).show();
try{
//SAX Resolved factory object
SAXParserFactory factory=SAXParserFactory.newInstance();
// get sax The parser
SAXParser saxParser=factory.newSAXParser();
// create handler object
XMLContentHandler handlerService=new XMLContentHandler();
InputStream is=getAssets().open("csdn.xml");
// Direct analytical
saxParser.parse(is, handlerService);
// through handlerService Object to obtain
Toast.makeText(XmlActivity.this,"----"+handlerService, Toast.LENGTH_LONG).show();
}catch(Exception e){
e.printStackTrace();
}
break;
case R.id.btn_dom:
InputStream is=null;
try{
// Gets the input stream object that reads the file
is=getAssets().open("csdn.xml");
// using dom parsing
List<Person> persons=xmlDomService.parseXML(is);
// A simple test
//Toast.makeText(XmlActivity.this, ""+persons.get(0).getName(), Toast.LENGTH_LONG).show();
Toast.makeText(XmlActivity.this," using DOM parsing "+persons.get(0).getName(), Toast.LENGTH_LONG).show();
}catch(Exception e){
e.printStackTrace();
}
break;
case R.id.btn_pull:
Toast.makeText(XmlActivity.this," using PULL parsing ", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}
}
I hope this article has been helpful in Android programming.