Simple example of Android XML data parsing

  • 2020-06-07 05:17:59
  • OfStack

1. Create XML data

Create the raw folder in the android project directory under the res/ directory and the data.xml folder in the raw project directory.

<?xml version="1.0" encoding="utf-8"?>
        <c studentNum="1">Android</c>
        <c studentNum="2">IPhone</c>

2. XML parsing code

import; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException; import android.os.Bundle;
import; public class MainActivity extends Activity {  @Override
 protected void onCreate(Bundle savedInstanceState) {
  InputStream is = getResources().openRawResource(;
  try {
   byte[] bytes = new byte[is.available()];;
   String XMLStr = new String(bytes,"utf-8");
   DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   Document doc = builder.parse(is);
   Node node = doc.getFirstChild();
   System.out.println(" The first 1 Child node "+node.getNodeName());
   NodeList list = doc.getElementsByTagName("c");
   NamedNodeMap map;
   for(int i = 0; i < list.getLength(); i++)
    node = list.item(i);
    map = node.getAttributes();
    System.out.println(node.getTextContent()+"  studentNum  "+map.getNamedItem("studentNum").getNodeValue());
  } catch (IOException e) {
   // TODO Auto-generated catch block
  } catch (ParserConfigurationException e) {
   // TODO Auto-generated catch block
  } catch (SAXException e) {
   // TODO Auto-generated catch block

Related articles: