首頁 >後端開發 >XML/RSS教程 >詳細介紹Xml資料解析的三種方式的範例程式碼

詳細介紹Xml資料解析的三種方式的範例程式碼

黄舟
黄舟原創
2017-03-08 16:22:171554瀏覽

一概述

xml作為一種資料互動格式,涉及到xml資料的產生與解析,這裡將講述Xml解析的三種方式。

二、Dom解析

1、建立解析器工廠物件(DocumentBuilderFactory物件)

2、建立解析器物件(DocumentBuilder)

#3、建立Document物件

例如解析下述檔案

<?xml version="1.0" encoding="utf-8"?>
<students>

        <student id = "1001">
             <id>1</id>
             <name>杨威</name>
             <address>大连</address>
             <age>21</age>
        </student>

        <student id = "1002">
             <id>2</id>
             <name>劉海洋</name>
             <address>深圳</address>
             <age>23</age>
        </student>

        <student id = "1003">
             <id>3</id>
             <name>王小波</name>
             <address>廣州</address>
             <age>22</age>
        </student>

</students>

解析程式碼如下

[code]package com.kuxiao.train.xml;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class XmlParseTest {

    public static void main(String[] args) throws Exception {

        //xml doc解析步骤
        //1、获取解析工厂对象
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //2、构建解析器对象
        DocumentBuilder   db = dbf.newDocumentBuilder();
        //3、构建docment对象
        Document  doc = db.parse(new File("person.xml"));

        Element ele = doc.getDocumentElement();

        //实现解析逻辑
        NodeList list = doc.getElementsByTagName("student");

        for(int i = 0; i < list.getLength();i++)
        {
              Element element = (Element) list.item(i);
              String attrid = element.getAttribute("id");
              System.out.println("attrid = " + attrid);
              Element  element1 = (Element) element.getElementsByTagName("id").item(0);
              String id = element1.getFirstChild().getNodeValue();
              System.out.println(id);
              element1 = (Element) element.getElementsByTagName("name").item(0);
              String name = element1.getFirstChild().getNodeValue();
              System.out.println(name);
              element1 = (Element) element.getElementsByTagName("address").item(0);
              String address = element1.getFirstChild().getNodeValue();
              System.out.println(address);

        }       

    }

}

三、注意事項

1、Element ele = doc.getDocumentElement( ); 取得根元素

2、取得到元素時,元素的值也是節點,必須element.getFirstChild().getNodeValue()方法取值。

3、xml中的空白也是Node,text類型的。

四、SAX解析

1、建立SAXParserFactory物件

2、建立SAXparser物件

3、建立MyHandler繼承DefaultHandler類,重寫方法。

4、sp.parse(new File(“student.xml”), new MyHandler(list));

[code]package com.kuxiao.train.xml.sax;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class TestSax {

    public static void main(String[] args) throws Exception {

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        List<Student> list = new ArrayList<>();
        sp.parse(new File("student.xml"), new MyHandler(list));
        System.out.println(list);

    }
}

class MyHandler extends DefaultHandler {

    private Stack<String> stack = new Stack<>();
    private Student student;
    private List<Student> mList = null;

    public MyHandler(List<Student> list)
    {
          this.mList = list;
    }
    @Override
    public void startDocument() throws SAXException {

        System.out.println("解析文档开始了...");
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
            if(qName.equals("学生"))
            {
                student = new Student();
                if(attributes.getLength() != 0)
                {
                     for(int i = 0; i < attributes.getLength();i++)
                     {
                            String id = attributes.getValue(i);
                            student.setId(Integer.parseInt(id));
                     }
                }
            }
            /*if(qName.equals("姓名"))
            {
                 stack.push(qName);
            }
            if(qName.equals("年龄"))
            {
                 stack.push(qName);
            }
            if(qName.equals("性别"))
            {
                 stack.push(qName);
            }*/
            stack.push(qName);
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
             String qName = stack.peek();
            if(qName.equals("性别")){
                student.setGender(new String(ch,start,length));
            }
            if(qName.equals("姓名")){
                student.setName(new String(ch,start,length));
            }
            if(qName.equals("年龄")){
                student.setAge(new String(ch,start,length));
            }
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
            stack.pop();
            if(qName.equals("学生"))
            {
                mList.add(student);
                student = null;
            }
    }

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

}

SAX是基於事件模型的,順序解析的,內部實作是觀察者模式,優點在於佔用記憶體少,效率高,缺點在編碼相對較複雜。

五、Pull解析

1、此解析方式不是JDK自帶的,需要導入第三方函式庫

2、建立XmlPullParserFactory物件

#3 、建立XmlPullParser物件

4、呼叫xpp.setInput(is,”utf-8”)

#5、對應事件類型處理xpp.next()下一個事件類型

[code]package com.kuxiao.train.xml.pull;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

public class PullTest {

    public static void main(String[] args) throws Exception {

        FileInputStream is = new FileInputStream(new File("person.xml"));
        long time = System.currentTimeMillis();
        List<Student> list = new ArrayList<>();
        XmlPullParserFactory xppf = XmlPullParserFactory.newInstance();
        XmlPullParser xpp = xppf.newPullParser();

        xpp.setInput(is, "utf-8");
        Student student = null;
        int eventType = xpp.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {

            switch (eventType) {
            case XmlPullParser.START_TAG:

                if (xpp.getName().equals("student")) {
                    student = new Student();
                    String id = xpp.getAttributeValue(0);
                    student.setId(id);
                } else if (xpp.getName().equals("name")) {
                    student.setName(xpp.nextText());

                } else if (xpp.getName().equals("address")) {
                    student.setAddress(xpp.nextText());
                } else if (xpp.getName().equals("age")) {
                    student.setAge(xpp.nextText());
                }
                break;
            case XmlPullParser.START_DOCUMENT:
                System.out.println("开始了....");
                break;
            case XmlPullParser.END_TAG:
                if (xpp.getName().equals("student")) {
                    list.add(student);
                    student = null;
                }
                break;
            }
            eventType = xpp.next();
        }

        is.close();
        long time1 = System.currentTimeMillis();
        System.out.println(time1 - time);
        for (Student student2 : list) {
            System.out.println(student2);
        }

        FileInputStream fis = new FileInputStream(new File("person.xml"));
        List<Student> list1 = getListBean(fis, new String[] { "id", "name",
                "address", "age", "gender" }, Student.class, 0);
        for (Student student2 : list1) {
            System.out.println(student2);
        }

    }
   //封装的全能解析xml文件的方法 
   //参数说明
   //attrs是文件里bean对象的元素与属性名
   //clazz是Bean对象的class对象
   //j代表属性的个数
    public static <T> List<T> getListBean(InputStream is, String[] attrs,
            Class<T> clazz, int j) throws Exception {
        long time = System.currentTimeMillis();
        T c = null;
        XmlPullParserFactory xppf = XmlPullParserFactory.newInstance();
        XmlPullParser xpp = xppf.newPullParser();
        xpp.setInput(is, "utf-8");
        List<T> list = null;
        int eventType = xpp.getEventType();
        String classname = "";

        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
            case XmlPullParser.START_TAG:
                int bigen = clazz.getName().lastIndexOf(".") + 1;
                classname = clazz.getName().substring(bigen);
                classname = classname.substring(0, 1).toLowerCase()
                        + classname.substring(1);
                String elementName = xpp.getName();

                if (classname.equals(elementName)) {

                    c = clazz.newInstance();
                    if (xpp.getAttributeCount() != 0) {
                        for (int i = 0; i < j; i++) {
                            String attrName = xpp.getAttributeName(i);
                            for (String field : attrs) {

                                if (field.equals(attrName)) {
                                    String frist = field.substring(0, 1)
                                            .toUpperCase();
                                    Method method = clazz.getDeclaredMethod(
                                            "set" + frist + field.substring(1),
                                            new Class[] { String.class });
                                    method.setAccessible(true);
                                    method.invoke(c, xpp.getAttributeValue(i));
                                }

                            }
                        }
                    }

                } else {
                    for (String field : attrs) {

                        if (field.equals(elementName)) {

                            String frist = field.substring(0, 1).toUpperCase();
                            Method method = clazz.getDeclaredMethod("set"
                                    + frist + field.substring(1),
                                    new Class[] { String.class });
                            method.setAccessible(true);
                            method.invoke(c, xpp.nextText());
                        }

                    }
                }

                break;
            case XmlPullParser.START_DOCUMENT:
                list = new ArrayList<T>();
                break;

            case XmlPullParser.END_TAG:
                if (!classname.equals("") && classname.equals(xpp.getName())) {
                    list.add(c);
                    c = null;
                }
                break;
            }
            eventType = xpp.next();
        }
        is.close();
        long time1 = System.currentTimeMillis();
        System.out.println(time1 - time);
        return list;
    }

}

#

以上是詳細介紹Xml資料解析的三種方式的範例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn