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"?>
<data>
    <class>
        <c studentNum="1">Android</c>
        <c studentNum="2">IPhone</c>
    </class>
</data>

2. XML parsing code


import java.io.IOException;
import java.io.InputStream; 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 android.app.Activity; public class MainActivity extends Activity {  @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  InputStream is = getResources().openRawResource(R.raw.data);
  try {
   byte[] bytes = new byte[is.available()];
   is.read();
   String XMLStr = new String(bytes,"utf-8");
   is.reset();
   System.out.println(XMLStr);
   
   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
   e.printStackTrace();
  } catch (ParserConfigurationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SAXException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}


Related articles: