1、创建XML数据
在android工程目录中res/目录下创建raw文件夹,在raw文件夹内创建data.xml。
2、XML解析代码
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("第一个子节点"+node.getNodeName());
NodeList list = doc.getElementsByTagName("c");
NamedNodeMap map;
for(int i = 0; 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();
}
}
}