1. 程式人生 > >如何解析本地和線上XML檔案獲取相應的內容

如何解析本地和線上XML檔案獲取相應的內容

一、使用Dom解析本地XML
1、本地XML檔案為:test.xml

<?xml version="1.0" encoding="UTF-8"?>
<Books>
  <Book id="1">
    <bookName>think in java</bookName>
    <bookAuthor>張三</bookAuthor>
    <bookISBN></bookISBN>
    <bookPrice>75.00</bookPrice>
  </Book
>
<Book id="2"> <bookName>java核心基礎</bookName> <bookAuthor>王二</bookAuthor> <bookISBN></bookISBN> <bookPrice>65.00</bookPrice> </Book> <Book id="3"> <bookName>Oracle</bookName> <bookAuthor>李四</bookAuthor
>
<bookISBN></bookISBN> <bookPrice>75.00</bookPrice> </Book> </Books>

2、建立book類儲存解析出來的內容

package com.yc.domain;

public class Book {
    private  int id;
    private String bookName;
    private String bookAuthor;
    private String bookISBN;
    private
String bookPrice; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getBookAuthor() { return bookAuthor; } public void setBookAuthor(String bookAuthor) { this.bookAuthor = bookAuthor; } public String getBookISBN() { return bookISBN; } public void setBookISBN(String bookISBN) { this.bookISBN = bookISBN; } public String getBookPrice() { return bookPrice; } public void setBookPrice(String bookPrice) { this.bookPrice = bookPrice; } @Override public String toString() { return "Book [id=" + id + ", bookName=" + bookName + ", bookAuthor=" + bookAuthor + ", bookISBN=" + bookISBN + ", bookPrice=" + bookPrice + "]"; } }

3、使用Dom解析:檔名為TestDom.java

package com.yc.utils;

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

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 com.yc.domain.Book;

public class TestDom {
    public List<Book> getBook(File file){
        List<Book> bookList=new ArrayList<Book>();
        try {
            //建立一個文件構建工廠
            DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
            //通過工廠生產DocumentBuilder物件
            DocumentBuilder builder=factory.newDocumentBuilder();
            //將指定file的內容解析  返回一個Document的物件
            Document doc=builder.parse(file);
            Element element=doc.getDocumentElement();//獲取根元素
            //System.out.println(element);
            NodeList nodeList=doc.getElementsByTagName("Book");
            //System.out.println(nodeList.getLength());
            int len=nodeList.getLength();
            for (int i = 0; i < len; i++) {
                Book  book=new Book();
                Node node=nodeList.item(i);
                book.setId(Integer.parseInt(node.getAttributes().getNamedItem("id").getNodeValue()));
                int len2=nodeList.item(i).getChildNodes().getLength();
                for (int j = 0; j < len2; j++) {
                    Node node1=nodeList.item(i).getChildNodes().item(j);
                    if(node1.getNodeType()==1){
                        String content=node1.getFirstChild().getNodeValue();
                        String nodeName=node1.getNodeName();
                        switch (nodeName) {
                        case "bookName":
                             book.setBookName(content);
                            break;
                        case "bookAuthor":
                            book.setBookAuthor(content);
                            break;
                        case "bookISBN":
                            book.setBookISBN(content);
                            break;
                        case "bookPrice":
                            book.setBookPrice(content);
                            break;

                        default:
                            break;
                        }
                    }
                }
                bookList.add(book);
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bookList;
    }
    public static void main(String[] args) {
        TestDom td=new TestDom();
        File file=new File("test.xml");
        List<Book> list=td.getBook(file);
        for (int i = 0; i <list.size(); i++) {
            Book book=list.get(i);
            System.out.println(book.toString());
            }
    }
}

4、解析結果:

Book [id=1, bookName=think in java, bookAuthor=張三, bookISBN=家, bookPrice=75.00]
Book [id=2, bookName=java核心基礎, bookAuthor=王二, bookISBN=家, bookPrice=65.00]
Book [id=3, bookName=Oracle, bookAuthor=李四, bookISBN=家, bookPrice=75.00]

二、使用Dom4j解析本地XML檔案
其他同上只是換用不同的解析方法:
本次使用Dom4j解析本地檔案test.xml

package com.yc.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.yc.domain.Book;

public class TestDom4j {
    public static void main(String[] args) {
        TestDom4j td=new TestDom4j();
        File file=new File("test.xml");
        List<Book> list=td.findAll(file);
        for (int i = 0; i <list.size(); i++) {
            Book book=list.get(i);
            System.out.println(book.toString());
            }
    }
    public List<Book> findAll(File file){
        List<Book>  bookList=new ArrayList<Book>();
        SAXReader  reader=new SAXReader();
        Document doc=null;
        try {
            doc=reader.read(file);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element  root=doc.getRootElement();//取出根節點
        //System.out.println(root);
        //迭代出所有子節點
        Iterator  its=root.elementIterator();
        Book  book=null;
        while(its.hasNext()){
            Element et=(Element) its.next();//取出所有book節點
            if("Book".equals(et.getName())){
                book=new Book();
                //迭代屬性
                for(Iterator  attrIts=et.attributeIterator();attrIts.hasNext();){
                    Attribute attr=(Attribute) attrIts.next();
                    if("id".equals(attr.getName())){
                        book.setId(Integer.parseInt(attr.getValue()));
                    }
                }
                //迭代Book地下元素
                for(Iterator it=et.elementIterator();it.hasNext();){
                    Element el=(Element) it.next();
                    switch (el.getName()) {
                    case "bookName":
                        book.setBookName(el.getText());
                        break;
                    case "bookAuthor":
                        book.setBookAuthor(el.getText());
                        break;
                    case "bookISBN":
                        book.setBookISBN(el.getText());
                        break;
                    case "bookPrice":
                        book.setBookPrice(el.getText());
                        break;
                    default:
                        break;
                    }

                }
            }
            bookList.add(book);
        }
        return bookList;
    }
}

解析結果同上
三、使用Sax解析本地檔案
其它同上只是換種解析方法
1.配置Sax檔案顯示解析過程

package com.yc.utils;

import java.util.ArrayList;
import java.util.List;

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

import com.yc.domain.Book;

public class SaxXML extends DefaultHandler {
    private List<Book> bookList;
    private Book book;
    private String tagName;//存放每一次存放的標籤
    //當我解析器解析  觸發方法
    @Override
    public void startDocument() throws SAXException {
        bookList=new ArrayList<Book>();
        System.out.println("開始讀文件了");
    }
    //當解析到元素節點時  觸發這個方法
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        System.out.println("開始讀元素了");
        if("Book".equals(qName)){
            book=new Book();
            book.setId(Integer.parseInt(attributes.getValue("id")));
        }
        tagName=qName;
    }
    //當每次解析文字節點就呼叫這個
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        System.out.println("文字解析中");
        if(book!=null){
            String content=new String(ch,start,length);
            if("bookName".equals(tagName)){
                book.setBookName(content);
            }else if("bookAuthor".equals(tagName)){
                book.setBookAuthor(content);
            }else if("bookISBN".equals(tagName)){
                book.setBookISBN(content);
            }else if("bookPrice".equals(tagName)){
                book.setBookPrice(content);
            }
        }
    }
    @Override
    public void endDocument() throws SAXException {
        System.out.println("文件結束了");
    }
    //元素結束
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        System.out.println("元素結束了");
        if("Book".equals(qName)){
            bookList.add(book);
            book=null;
            }
        tagName="";

    }
    public List<Book> getBookList() {
        return bookList;
    }

}

2、使用Sax解析本地檔案test.xml

package com.yc.utils;

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

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

import org.xml.sax.SAXException;

import com.yc.domain.Book;

public class TestSax {
    public List<Book> findAll(File file){
        List<Book> bookList=new ArrayList<Book>();
        //獲取SAX解析工廠
        SAXParserFactory spf= SAXParserFactory.newInstance();
        try {
            SAXParser parser=spf.newSAXParser();
            SaxXML sx=new SaxXML();
            parser.parse(file, sx);
            bookList=sx.getBookList();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bookList;
    }
    public static void main(String[] args) {
        TestSax ts=new TestSax();
        File file=new File("test.xml");
        List<Book> list=ts.findAll(file);
        for (Book book:list) {
            System.out.println(book.toString());
        }
    }

}

3.解析結果:

開始讀文件了
開始讀元素了
文字解析中
開始讀元素了
文字解析中
開始讀元素了
文字解析中
元素結束了
文字解析中
開始讀元素了
文字解析中
元素結束了
文字解析中
開始讀元素了
文字解析中
元素結束了
文字解析中
開始讀元素了
文字解析中
元素結束了
文字解析中
元素結束了
文字解析中
開始讀元素了
文字解析中
開始讀元素了
文字解析中
元素結束了
文字解析中
開始讀元素了
文字解析中
元素結束了
文字解析中
開始讀元素了
文字解析中
元素結束了
文字解析中
開始讀元素了
文字解析中
元素結束了
文字解析中
元素結束了
文字解析中
開始讀元素了
文字解析中
開始讀元素了
文字解析中
元素結束了
文字解析中
開始讀元素了
文字解析中
元素結束了
文字解析中
開始讀元素了
文字解析中
元素結束了
文字解析中
開始讀元素了
文字解析中
元素結束了
文字解析中
元素結束了
文字解析中
元素結束了
文件結束了
Book [id=1, bookName=think in java, bookAuthor=張三, bookISBN=家, bookPrice=75.00]
Book [id=2, bookName=java核心基礎, bookAuthor=王二, bookISBN=家, bookPrice=65.00]
Book [id=3, bookName=Oracle, bookAuthor=李四, bookISBN=家, bookPrice=75.00]
<?xml version="1.0"?>
<NewsResult>
  <error_code>0</error_code>
  <reason>Succes</reason>
  <result>
    <NewsObj>
      <ctime>2016-08-28 00:21</ctime>
      <title>俄羅斯莫斯科倉庫大火致16人死亡4人受傷</title>
      <description>網易國內</description>
      <picUrl>http://s.cimg.163.com/cnews/2016/8/28/2016082800201872c58_550.jpg.119x83.jpg</picUrl>
      <url>http://news.163.com/16/0828/00/BVH193060001121M.html#f=dlist</url>
    </NewsObj>
    <NewsObj>
      <ctime>2016-08-27 19:41</ctime>
      <title>江浙兩省新任副省長均出身企業 未在政府工作過</title>
      <description>網易國內</description>
      <picUrl>http://s.cimg.163.com/catchpic/8/8B/8B6D4CBC561C0DC041A842C539584115.jpg.119x83.jpg</picUrl>
      <url>http://news.163.com/16/0827/19/BVGH7F1S0001124J.html#f=dlist</url>
    </NewsObj>
    <NewsObj>
      <ctime>2016-08-27 17:30</ctime>
      <title>國務院這幾年聘任的“智囊”都有誰?</title>
      <description>網易國內</description>
      <picUrl>http://s.cimg.163.com/photo/0001/2016-08-26/t_BVCOE4IO6VVV0001.jpg.119x83.jpg</picUrl>
      <url>http://news.163.com/16/0827/17/BVG9OSRD00014SEH.html#f=dlist</url>
    </NewsObj>
    <NewsObj>
      <ctime>2016-08-27 17:43</ctime>
      <title>山東警方深化打擊治理網路電信詐騙違法犯罪 電信詐騙</title>
      <description>網易國內</description>
      <picUrl>http://s.cimg.163.com/catchpic/1/1E/1E766CCB83F19FCD738C223989B52C14.jpg.119x83.jpg</picUrl>
      <url>http://news.163.com/16/0827/17/BVGAG3OF00014SEH.html#f=dlist</url>
    </NewsObj>
    <NewsObj>
      <ctime>2016-08-27 18:48</ctime>
      <title>廣西東興市發生一起中毒事故 已造成3人死亡</title>
      <description>網易國內</description>
      <picUrl>http://s.cimg.163.com/catchpic/9/91/916E9B868A41E063AB768112E4016DE1.jpg.119x83.jpg</picUrl>
      <url>http://news.163.com/16/0827/18/BVGE6V82000146BE.html#f=dlist</url>
    </NewsObj>
    <NewsObj>
      <ctime>2016-08-27 14:38</ctime>
      <title>內地奧運精英代表團開啟3日訪港之旅,將與當地民眾互</title>
      <description>網易國內</description>
      <picUrl>http://s.cimg.163.com/catchpic/7/76/7673DDB4A375F3CE365A27E05D3551C8.jpg.119x83.jpg</picUrl>
      <url>http://news.163.com/16/0827/14/BVFVTQSD00014SEH.html#f=dlist</url>
    </NewsObj>
    <NewsObj>
      <ctime>2016-08-27 14:46</ctime>
      <title>麗江女官員被開除公職 多次與人發生不正當性關係</title>
      <description>網易國內</description>
      <picUrl>http://s.cimg.163.com/cnews/2016/8/27/20160827144553a4f90.jpg.119x83.jpg</picUrl>
      <url>http://news.163.com/16/0827/14/BVG0BKN70001124J.html#f=dlist</url>
    </NewsObj>
    <NewsObj>
      <ctime>2016-08-27 15:28</ctime>
      <title>甘肅張掖航空大會遇難飛行員為南非籍(圖)</title>
      <description>網易國內</description>
      <picUrl>http://s.cimg.163.com/cnews/2016/8/27/20160827112149ecd50.gif.119x83.jpg</picUrl>
      <url>http://news.163.com/16/0827/15/BVG2OPMO00014JB6.html#f=dlist</url>
    </NewsObj>
    <NewsObj>
      <ctime>2016-08-27 15:37</ctime>
      <title>哈爾濱劉亞樓舊居等被毀不可移動文物擬原址重建</title>
      <description>網易國內</description>
      <picUrl>http://s.cimg.163.com/photo/0001/2016-08-26/t_BVCOE4IO6VVV0001.jpg.119x83.jpg</picUrl>
      <url>http://news.163.com/16/0827/15/BVG39ELT0001124J.html#f=dlist</url>
    </NewsObj>
    <NewsObj>
      <ctime>2016-08-27 15:56</ctime>
      <title>河北唐山市古冶區發生3.1級地震 震源深度10千米</title>
      <description>網易國內</description>
      <picUrl>http://s.cimg.163.com/catchpic/1/1E/1E766CCB83F19FCD738C223989B52C14.jpg.119x83.jpg</picUrl>
      <url>http://news.163.com/16/0827/15/BVG4C7SD0001124J.html#f=dlist</url>
    </NewsObj>
  </result>
</NewsResult>

3.建立News類儲存解析內容

package com.yc.domain;

public class News {
    private String ctime;
    private String title;
    private String description;
    private String picUrl;
    private String url;
    public String getCtime() {
        return ctime;
    }
    public void setCtime(String ctime) {
        this.ctime = ctime;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getPicUrl() {
        return picUrl;
    }
    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    @Override
    public String toString() {
        return "News [ctime=" + ctime + ", title=" + title + ", description="
                + description + ", picUrl=" + picUrl + ", url=" + url + "]";
    }



}

4.解析線上新聞XML檔案

package com.yc.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

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 com.yc.domain.Book;
import com.yc.domain.News;

public class TestNews {

    public static void main(String[] args) {
        List<News> newsList=new ArrayList<News>();

            try {
                File file=new File("news.xml");
                if(!file.exists()){
                    URL url=new URL("http://api.avatardata.cn/GuoNeiNews/Query?key=b5884e12578141e888cf17fe62903bd2&page=1&rows=10&dtype=xml");
                    URLConnection con=url.openConnection();
                    con.connect();
                    InputStream is=con.getInputStream();
                    OutputStream os=new FileOutputStream(file,true);
                    byte[] bt=new byte[1024];
                    int len=-1;
                    while((len=is.read(bt))!=-1){
                        os.write(bt,0,len);
                    }
                    os.flush();
                    os.close();
                    is.close();
                }
                /*URL url=new URL("http://api.avatardata.cn/GuoNeiNews/Query?key=b5884e12578141e888cf17fe62903bd2&page=1&rows=10&dtype=xml");
                URLConnection con=url.openConnection();
                con.connect();
                InputStream is=con.getInputStream();*/
                DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
                DocumentBuilder builder=factory.newDocumentBuilder();
                Document doc=builder.parse(file);
                Element  element=doc.getDocumentElement();
                //System.out.println(element);
                NodeList  n1=doc.getElementsByTagName("NewsObj");
                //System.out.println(n1.getLength());
                int len=n1.getLength();
                for (int i = 0; i < len; i++) {
                    News news=new News();
                    Node node=n1.item(i);
                    int len2=n1.item(i).getChildNodes().getLength();
                    for (int j = 0; j < len2; j++) {
                        Node node1=n1.item(i).getChildNodes().item(j);
                        if(node1.getNodeType()==1){
                            String content=node1.getFirstChild().getNodeValue();
                            String nodeName=node1.getNodeName();
                            switch (nodeName) {
                            case "ctime":
                                news.setCtime(content);
                                break;
                            case "title":
                                news.setTitle(content);
                                break;
                            case "description":
                                news.setDescription(content);
                                break;
                            case "picUrl":
                                news.setPicUrl(content);
                                break;
                            case "url":
                                news.setUrl(content);
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    newsList.add(news);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            }
            for (int i = 0; i <newsList.size(); i++) {
                News news=newsList.get(i);
                System.out.println(news.toString());
                }

    }

}