1.DOM解析
DOM方式解析xml是先把xml文档都读到内存中,然后再用DOM API来访问树形结构,并获取数据的,但是这样一来,如果xml文件很大呢?手机CPU处理能力当然不能与PC机器比,因此在处理性能上会有折损。所以如果XML文件比较大,建议还是用下面两种方式,而不用DOM方式。
DOM解析的步骤一般如下:
1.构建一个DocumentBuilderFactory实例
2.构建DocumentBuilder
3.加载XML文档(Document)
4.遍历XML文档
private List<Person> parseByDomParser() throws ParserConfigurationException, SAXException, IOException { List<Person> resList = new ArrayList<Person>(); // 构建一个DocumentBuilderFactory实例 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 构建DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder(); // 读取文件流 AssetManager assetManager=getAssets(); InputStream stream=assetManager.open("customers.xml"); //InputStream stream = getResources().openRawResource(R.raw.customers); // 得到代表整个xml的Document对象 Document document = builder.parse(stream); // 遍历所有节点 Element root = document.getDocumentElement(); // 获取根节点的所有customer的节点 NodeList nodes = root.getElementsByTagName("customer"); for (int index = 0; index < nodes.getLength(); index++) { Person person = new Person(); // 获取person元素节点