[java開發篇][dom模塊] 遍歷解析xml


http://blog.csdn.net/andie_guo/article/details/24844351

XML DOM節點樹

XML DOM將XML文檔作為樹結構,樹結構稱為一個節點樹。所有的節點可以通過樹訪問,它們的內容可以被修改或刪除,也可以建立新的元素。節點樹用於顯示節點集和它們之間的聯系。下圖呈現的是books.XML文件的節點樹。

常用的幾個對象:

1)Element類:

是Node類最主要的子對象,被廣泛使用,在元素中可以包含屬性,因而Element中有存取其屬性的方法。

2)Node類:

Node對象是DOM中最基本的對象,代表了文檔樹中的抽象節點。但在實際使用中很少會直接使用Node對象,而是使用Node對象的子對象Element,Attr,Text等。

3)NodeList類:

代表了一個包含一個或者多個Node的列表,根據操作可以將其簡化的看做為數組。

 

DOM XML Parser 解析XML文件

<?xml version="1.0" encoding="UTF-8"?>  
<!-- Edited by XMLSpy -->  
<bookstore>  
    <book category="cooking">  
        <title lang="en">Everyday Italian</title>  
        <author>Giada De Laurentiis</author>  
        <year>2005</year>  
        <price>30.00</price>  
    </book>  
    <book category="children">  
        <title lang="en">Harry Potter</title>  
        <author>J K. Rowling</author>  
        <year>2005</year>  
        <price>29.99</price>  
    </book>  
    <book category="web">  
        <title lang="en">XQuery Kick Start</title>  
        <author>James McGovern</author>  
        <author>Per Bothner</author>  
        <author>Kurt Cagle</author>  
        <author>James Linn</author>  
        <author>Vaidyanathan Nagarajan</author>  
        <year>2003</year>  
        <price>49.99</price>  
    </book>  
    <book category="web" cover="paperback">  
        <title lang="en">Learning XML</title>  
        <author>Erik T. Ray</author>  
        <year>2003</year>  
        <price>39.95</price>  
    </book>  
</bookstore> 

 

Book.java:該對象是一個實體Bean,其字段信息對應着xml文件里的元素字段,由於篇幅有限,讀者自行生成get、set方法 。

package com.andieguo.xmldemo;  
  
public class Book {  
    private String category;  
    private String titleLang;  
    private String title;  
    private String author;  
    private Integer year;  
    private Double price;  
      
      
    @Override  
    public String toString() {  
        return "Book [category=" + category + ", titleLang=" + titleLang + ", title=" + title + ", author=" + author + ", year=" + year + ", price=" + price + "]";  
    }  
    //生成字段的get、set方法  
}

ReadXMLFile.java :解析XML文件並存入List<Book>集合。

package com.andieguo.xmldemo;  
  
import java.io.File;  
import java.util.ArrayList;  
import java.util.List;  
  
import javax.xml.parsers.DocumentBuilder;  
import javax.xml.parsers.DocumentBuilderFactory;  
  
import org.w3c.dom.Document;  
import org.w3c.dom.Element;  
import org.w3c.dom.Node;  
import org.w3c.dom.NodeList;  
  
public class ReadXMLFile {  
  
    public static void main(String[] args) {  
        File file = new File("src/com/andieguo/xmldemo/books.xml");//books.xml文件應放在和ReadXMLFile.java同級的文件夾下  
        List<Book> books = readXMLFile(file);  
        for (Book book : books) {  
            System.out.println(book.toString());  
        }  
    }  
  
    public static List<Book> readXMLFile(File file) {  
        List<Book> lists = new ArrayList<Book>();  
        try {  
  
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();  
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();  
            Document doc = dBuilder.parse(file);  
            NodeList bookList = doc.getElementsByTagName("book");  
            for (int i = 0; i < bookList.getLength(); i++) {  
                Node bookNode = bookList.item(i);  
                if (bookNode.getNodeType() == Node.ELEMENT_NODE) {  
                    Element bookElement = (Element) bookNode;  
                    Book book = new Book();  
                    book.setCategory(bookElement.getAttribute("category"));  
                    Element titleElement = (Element) bookElement.getElementsByTagName("title").item(0);  
                    book.setTitle(titleElement.getTextContent());  
                    book.setTitleLang(titleElement.getAttribute("lang"));  
                    NodeList authorList = bookElement.getElementsByTagName("author");  
                    String author = "";  
                    for (int j = 0; j < authorList.getLength(); j++) {  
                        author = author + authorList.item(j).getTextContent() + "/";  
                    }  
                    author = author.substring(0, author.length() - 1);  
                    book.setAuthor(author);  
                    book.setYear(Integer.valueOf(bookElement.getElementsByTagName("year").item(0).getTextContent()));  
                    book.setPrice(Double.valueOf(bookElement.getElementsByTagName("price").item(0).getTextContent()));  
                    lists.add(book);  
                }  
  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return lists;  
    }  
}

運行結果如圖所示:

 

  1. package com.andieguo.xmldemo;  
  2.   
  3. import java.io.File;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import javax.xml.parsers.DocumentBuilder;  
  8. import javax.xml.parsers.DocumentBuilderFactory;  
  9.   
  10. import org.w3c.dom.Document;  
  11. import org.w3c.dom.Element;  
  12. import org.w3c.dom.Node;  
  13. import org.w3c.dom.NodeList;  
  14.   
  15. public class ReadXMLFile {  
  16.   
  17.     public static void main(String[] args) {  
  18.         File file = new File("src/com/andieguo/xmldemo/books.xml");//books.xml文件應放在和ReadXMLFile.java同級的文件夾下  
  19.         List<Book> books = readXMLFile(file);  
  20.         for (Book book : books) {  
  21.             System.out.println(book.toString());  
  22.         }  
  23.     }  
  24.   
  25.     public static List<Book> readXMLFile(File file) {  
  26.         List<Book> lists = new ArrayList<Book>();  
  27.         try {  
  28.   
  29.             DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();  
  30.             DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();  
  31.             Document doc = dBuilder.parse(file);  
  32.             NodeList bookList = doc.getElementsByTagName("book");  
  33.             for (int i = 0; i < bookList.getLength(); i++) {  
  34.                 Node bookNode = bookList.item(i);  
  35.                 if (bookNode.getNodeType() == Node.ELEMENT_NODE) {  
  36.                     Element bookElement = (Element) bookNode;  
  37.                     Book book = new Book();  
  38.                     book.setCategory(bookElement.getAttribute("category"));  
  39.                     Element titleElement = (Element) bookElement.getElementsByTagName("title").item(0);  
  40.                     book.setTitle(titleElement.getTextContent());  
  41.                     book.setTitleLang(titleElement.getAttribute("lang"));  
  42.                     NodeList authorList = bookElement.getElementsByTagName("author");  
  43.                     String author = "";  
  44.                     for (int j = 0; j < authorList.getLength(); j++) {  
  45.                         author = author + authorList.item(j).getTextContent() + "/";  
  46.                     }  
  47.                     author = author.substring(0, author.length() - 1);  
  48.                     book.setAuthor(author);  
  49.                     book.setYear(Integer.valueOf(bookElement.getElementsByTagName("year").item(0).getTextContent()));  
  50.                     book.setPrice(Double.valueOf(bookElement.getElementsByTagName("price").item(0).getTextContent()));  
  51.                     lists.add(book);  
  52.                 }  
  53.   
  54.             }  
  55.         } catch (Exception e) {  
  56.             e.printStackTrace();  
  57.         }  
  58.         return lists;  
  59.     }  
  60. }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM