- XML parsing summary DOM SAX PULL MD

Markdown version notes My GitHub Home my blog My WeChat my mail box
MyAndroidBlogs baiqiantao baiqiantao bqt20094 [email protected]

table of Contents

XML parsing summary DOM SAX PULL MD

JDOM warehouse address
DOM4j warehouse address
XmlPull warehouse address

Android default has been introduced XmlPull, if the need to introduce yourself, you need to add the following two jar package at the same time:

Several analytical methods Introduction

Brief introduction

  • DOM parse: the xml files all loaded into memory, assembled into a dom tree, then to parse xml files through the relationship between nodes and node; understanding is relatively simple, but because the entire document needs to be loaded into memory, does not apply documents larger.
  • SAX parse: event-driven, one by one resolution, suitable for processing xml data only; not easy coding, and difficult to access many different data in the same document at the same time.
  • JDOM parse: mainly used to make up for the lack of DOM and SAX in practical application, to achieve faster than using DOM, use only a specific class rather than using the interface, thus simplifying the API, and easy to use.
  • DOM4j parse: JDOM branch of an intelligent, more powerful, it is recommended familiar with.
  • Pull parse: An analytical manner provided by Android, and similar to SAX parser, based on event-driven one by one resolution, but requires the use of parser.next()methods to extract them.

Pull parsing and analytic comparison Sax :

  • Pull parsing and Sax analytical similarity in the mode of operation, Pull Parser also provides a SAX-like event, starting document START_DOCUMENTand the end of the document END_DOCUMENT, start element START_TAGand end element, END_TAGand so on, but you need to call next()a method to extract them (active extracts event).
  • SAX parser works by automatically push the event into the event handler registration is processed, the processing of events you can not control the end of the initiative; and Pull parsers work actively to obtain from the parser to allow your application code event, because it is actively acquiring an event, it can no longer meet the conditions required to obtain after the event, the end of the resolution. This is their main difference.
  • Namely: SAX parsing the entire document will be resolved, and resolved to Pull parsing can control where you can stop halfway in the program.

To parse the content

<?xml version="1.0" encoding="utf-8"?>
<class>
  <string name="user">包青天</string>
  <string name="job" id="10086">Android开发</string>
  <student id="10010">
    <string name="user">白乾涛</string>
    <string name="job" id="100">码农</string>
  </student>
</class>

DOM parsing

Code

public static void domParseXml(String path) throws Exception {
    System.out.println("--------------------  DOM解析  --------------------");
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path);
    NodeList stringList = document.getElementsByTagName("string");
    domParseNode(stringList); //长度为4【user:包青天, null】【job:Android开发, 10086】【user:白乾涛, null】【job:码农, 100】

    NodeList studentList = document.getElementsByTagName("student");
    System.out.println("【" + studentList.getLength() + "】");

    for (int i = 0; i < studentList.getLength(); i++) {
        NamedNodeMap map = studentList.item(i).getAttributes();
        String id = map != null && map.getNamedItem("id") != null ? map.getNamedItem("id").getNodeValue() : null;
        System.out.println("id = " + id);

        NodeList childNodeList = studentList.item(i).getChildNodes();
        domParseNode(childNodeList); //长度为5(而不是2)【user:白乾涛, null】【job:码农, 100】
    }
}

private static void domParseNode(@NotNull NodeList nodeList) {
    System.out.println("【" + nodeList.getLength() + "】");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);  //获取第i个节点
        if (node != null && node.getFirstChild() != null) {
            NamedNodeMap map = node.getAttributes(); //获取此节点的所有属性
            if (map != null) {
                Node nameNode = map.getNamedItem("name"); //获取名为name的属性
                String nameNodeValue = nameNode != null ? nameNode.getNodeValue() : null; //获取属性的属性值,也可以使用getTextContent
                String nodeValue = node.getFirstChild().getNodeValue(); //获取节点的值

                Node idNode = map.getNamedItem("id"); //获取名为id的属性
                String idNodeValue = idNode != null ? idNode.getNodeValue() : null;
                System.out.println(nameNodeValue + ":" + nodeValue + ", " + idNodeValue);
            }
        }
    }
}

Export

--------------------  DOM 解析  --------------------
【4】
user:包青天, null
job:Android开发, 10086
user:白乾涛, null
job:码农, 100
【1】
id = 10010
【5】
user:白乾涛, null
job:码农, 100

SAX parsing

Code

System.out.println("--------------------  SAX解析  --------------------");
SAXParserFactory.newInstance().newSAXParser().parse(path, new SAXParseHandel());

SAXParseHandel

public class SAXParseHandel extends DefaultHandler {

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        System.out.println("开始解析");
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        System.out.println("结束解析");
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        //开始解析节点时调用此方法
        System.out.println("开始解析" + qName);

        for (int i = 0; i < attributes.getLength(); i++) {
            System.out.println("     " + attributes.getQName(i) + ":" + attributes.getValue(i));//此案例中:getLocalName和getQName一致 ,getType的值为CDATA
        }

        switch (qName) {
        case "student":
            int index = attributes.getIndex("id");//当节点名为student时,获取student的id属性
            System.out.println("   --" + attributes.getQName(index) + ":" + attributes.getValue(index));
            break;
        case "string":
            System.out.print("  -" + attributes.getValue(attributes.getIndex("name")) + ":");
            break;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        //节点解析完毕时调用此方法
        System.out.println("结束解析" + qName);
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        //此方法用来获取节点的值
        String value = new String(ch, start, length).trim();
        if (!value.equals("")) {
            System.out.println(value);
        }
    }
}

Export

--------------------  SAX 解析  --------------------
开始解析
开始解析class
开始解析string
     name:user
  -user:包青天
结束解析string
开始解析string
     name:job
     id:10086
  -job:Android开发
结束解析string
开始解析student
     id:10010
   --id:10010
开始解析string
     name:user
  -user:白乾涛
结束解析string
开始解析string
     name:job
     id:100
  -job:码农
结束解析string
结束解析student
结束解析class
结束解析

JDOM parsing

Code

public static void jdomParseXml(String path) throws Exception {
    System.out.println("--------------------  JDOM解析  --------------------");
    org.jdom2.Document document = new SAXBuilder().build(path);
    List<org.jdom2.Element> elementList = document.getRootElement().getChildren();

    for (org.jdom2.Element element : elementList) {
        jdomParseNode(element);

        //解析子节点
        for (org.jdom2.Element chileElement : element.getChildren()) {
            jdomParseNode(chileElement);
        }
    }
}

private static void jdomParseNode(@NotNull org.jdom2.Element element) {
    System.out.println(element.getName() + ":" + element.getTextTrim());

    //解析属性
    List<org.jdom2.Attribute> attributeList = element.getAttributes();
    for (org.jdom2.Attribute attribute : attributeList) {
        System.out.println("    " + attribute.getName() + ":" + attribute.getValue());
    }
}

Export

--------------------  JDOM 解析  --------------------
string:包青天
    name:user
string:Android开发
    name:job
    id:10086
student:
    id:10010
string:白乾涛
    name:user
string:码农
    name:job
    id:100

DOM4J resolve

Code

public static void dom4JParseXml(String path) throws Exception {
    System.out.println("--------------------  DOM4J解析  --------------------");
    org.dom4j.Document document = new SAXReader().read(path);
    Iterator iterator = document.getRootElement().elementIterator();

    while (iterator.hasNext()) {
        org.dom4j.Element element = (org.dom4j.Element) iterator.next();
        dom4JParseNode(element);

        //遍历子节点
        Iterator childIterator = element.elementIterator();
        while (childIterator.hasNext()) {
            dom4JParseNode((org.dom4j.Element) childIterator.next());
        }
    }
}

private static void dom4JParseNode(@NotNull org.dom4j.Element element) {
    System.out.println(element.getName() + ":" + element.getTextTrim());

    //解析属性
    for (Object object : element.attributes()) {
        org.dom4j.Attribute attribute = (org.dom4j.Attribute) object;
        System.out.println("    " + attribute.getName() + ":" + attribute.getValue());
    }
}

Export

--------------------  DOM4J 解析  --------------------
string:包青天
    name:user
string:Android开发
    name:job
    id:10086
student:
    id:10010
string:白乾涛
    name:user
string:码农
    name:job
    id:100

PULL resolve

Code

public static void pullParseXml(String path) throws Exception {
    System.out.println("--------------------  PULL解析  --------------------");
    InputStream inputStream = new FileInputStream(path);
    XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();

    parser.setInput(inputStream, "UTF-8");
    int eventType = parser.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT) { //文档结束
        switch (eventType) {
        case XmlPullParser.START_TAG://开始标签
            String name = parser.getName();
            System.out.println("开始解析 " + name + ", 行列:" + parser.getLineNumber() + "-" + parser.getColumnNumber() + ", 深度:" + parser.getDepth());
            for (int i = 0; i < parser.getAttributeCount(); i++) {
                //getAttributeType为【CDATA】,getAttributePrefix为【null】,getAttributeNamespace为空【】
                System.out.println("     " + parser.getAttributeName(i) + ":" + parser.getAttributeValue(i));//属性名及属性值
            }

            if ("string".equals(name)) {
                System.out.println(parser.nextText()); //获取节点的值
            }
            break;
        case XmlPullParser.END_TAG://结束标签
            System.out.println("结束解析" + parser.getName());
            break;
        }
        eventType = parser.next();//这一步很重要,该方法返回一个事件码,也是触发下一个事件的方法
    }
}

Export

--------------------  PULL 解析  --------------------
开始解析 class, 行列:2-8, 深度:1
开始解析 string, 行列:3-23, 深度:2
     name:user
包青天
开始解析 string, 行列:4-33, 深度:2
     name:job
     id:10086
Android开发
开始解析 student, 行列:5-23, 深度:2
     id:10010
开始解析 string, 行列:6-25, 深度:3
     name:user
白乾涛
开始解析 string, 行列:7-33, 深度:3
     name:job
     id:100
码农
结束解析student
结束解析class

2019-11-23

Guess you like

Origin www.cnblogs.com/baiqiantao/p/11919687.html