DOM解析

来源:互联网 发布:tensorflow 汉字识别 编辑:程序博客网 时间:2024/06/06 01:12

网络传输数据最常用的格式有两种:XML和JSON。XML的优势在于无视平台,在任何平台都能使用,且使用范围广,而JSON的优势在于解析简单,看起来一目了然。

今天主要讲的是XML解析的方法:XML常用的解析方法有三种DOM解析,SAX解析以及PULL解析。前面两种属于java的解析方式,而后者只能在Android使用。

下面介绍一下DOM解析的基本方式:

package com.example.internetdemo;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.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;import android.content.Context;import android.content.res.Resources;public class DomParserDemo {/** *  * @param context * @throws ParserConfigurationException *             -->解析设置异常 * @throws IOException * @throws SAXException */public static void domParser(Context context) throws ParserConfigurationException,SAXException, IOException {Resources resources = context.getResources();// 将xml文件转成输入流InputStream stream = resources.openRawResource(R.raw.person);// 抽象类:获取dom解析器工厂的对象DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();// dom解析器对象DocumentBuilder db = dbf.newDocumentBuilder();// 解析器解析流对象获取Document对象Document document = db.parse(stream);//获取整个文档元素(指的是所有标签)Element documentElement = document.getDocumentElement();//获取标签节点集合NodeList nodeList = documentElement.getElementsByTagName("person");for (int i = 0; i < nodeList.getLength(); i++) {//获取节点元素Node node = nodeList.item(i);//节点名字//node.getNodeName();//将节点强转成元素对象Element eachPerson = (Element) node;//获取id属性对应的值String id = eachPerson.getAttribute("id");//当前节点的所有子节点NodeList childNodes = eachPerson.getChildNodes();String name = "";String age = "";for (int j = 0; j < childNodes.getLength(); j++) {Node item = childNodes.item(j);//可能在当前节点头标签和尾标签写一个值,也算一个节点,但是该节点不是一个元素//所以不能转成元素,可能会出现强转异常,只有有标签的才能转成元素if (item instanceof Element) {Element element = (Element) item;//获取节点的名字String nodeName = element.getNodeName();if ("name".equals(nodeName)) {//获取节点值//name = element.getNodeValue();NodeList nodes = element.getChildNodes();Node item2 = nodes.item(0);name = item2.getNodeValue();}else if ("age".equals(nodeName)) {//age = element.getNodeValue();NodeList nodes = element.getChildNodes();Node item2 = nodes.item(0);age = item2.getNodeValue();}}}System.out.println("id---"+id+",name---"+name+",age----"+age);}}}

此处我解析的是自定义的XML文件,如下:

<?xml version="1.0" encoding="utf-8"?><person>    <person id="1">        <name>mike</name>        <age>20</age>    </person><person id="2">        <name>jack</name>        <age>22</age>    </person>    <person id="3">        <name>rose</name>        <age>21</age>    </person></person>
如果要解析网络的XML文件,只需使用HttpUrlConnection或者HttpClient进行网络连接,获取输入流即可。

0 0
原创粉丝点击