解析一个XML文件在实际项目中经常要用到,常用的有两种方式:DOM和SAX方式。它们的之间有很大的区别:DOM是把XML文件以一棵树的形式装载到内存里,然后再对它进行遍历,进而获得XML文件中存储的信息。而SAX解析方式是一种流机制的解析方式,它是读一行XML文件解析一行。
例如,XML文件如下:
<?xml version="1.0" encoding="utf-8"?><Students><student id="1"><name>杨振宇</name><sno>2008011123</sno><sex>男</sex><phone>18618405551</phone></student><student id="2"><name>张瑞</name><sno>2008011122</sno><sex>男</sex><phone>15120058124</phone></student><student id="3"><name>陈明</name><sno>2008011121</sno><sex>男</sex><phone>15801281851</phone></student><student id="4"><name>苏玉杰</name><sno>2008011120</sno><sex>男</sex><phone>18618405551</phone></student><student id="5"><name>高阳</name><sno>2008011145</sno><sex>女</sex><phone>18618405590</phone></student></Students>可以用一下的方式进行解析:public static void parse(File file) throws Exception {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder();Document doc = builder.parse(file);Element root = doc.getDocumentElement();NodeList childList = root.getChildNodes();for (int i = 0; i < childList.getLength(); i++) {Node child = childList.item(i);if (child instanceof Element) {
Element element = (Element) child;NodeList childInfo = element.getChildNodes();for (int j = 0; j < childInfo.getLength(); j++) {Node node = childInfo.item(j);if (node instanceof Element) {
Element e = (Element) node;Log.v("tag", "" + e.getTagName());Text textNode = (Text) e.getFirstChild();String text = textNode.getData().trim();if (e.getTagName().equals("name"))Log.v("tag", "" + text);else if (e.getTagName().equals("sno"))Log.v("tag", "" + text);else if (e.getTagName().equals("sex"))Log.v("tag", "" + text);else if (e.getTagName().equals("phone"))Log.v("tag", "" + text);}}}}}这样就可以把XML文件的有关信息给获取出来。