1. Create XML data
Create the Raw folder under the Res/directory in the Android project directory and create the Data.xml in the Raw folder.
Copy Code code as follows:
<?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
Copy Code code as follows:
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 ("First 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 ();
}
}
}