必威体育Betway必威体育官网
当前位置:首页 > IT技术

Java解析XML文件

时间:2019-08-11 19:13:18来源:IT技术作者:seo实验室小编阅读:73次「手机版」
 

解析xml

1.DOM方式解析XML

Dom解析是将xml文件全部载入到内存,组装成一颗dom树,然后通过节点以及节点之间的关系来解析xml文件,与平台无关,java提供的一种基础的解析XML文件的API,理解较简单,但是由于整个文档都需要载入内存,不适用于文档较大时。

2.SAX方式解析XML

基于事件驱动,逐条解析,适用于只处理xml数据,不易编码,而且很难同时访问同一个文档中的多处不同数据

3.JDOM方式解析XML

简化与XML的交互并且比使用DOM实现更快,仅使用具体类而不使用接口因此简化了API,并且易于使用

4.DOM4j方式解析XML

JDOM的一种智能分支,功能较强大,建议熟练使用

下面给出例子:

books.xml

[html] view plain copy print?

  1. <?xmlversion=“1.0”encoding=“UTF-8”?>
  2. <bookstore>
  3. <bookid=“1”>
  4. <name>冰与火之歌</name>
  5. <author>乔治马丁</author>
  6. <year>2014</year>
  7. <price>89</price>
  8. </book>
  9. <bookid=“2”>
  10. <name>安徒生童话</name>
  11. <author>安徒生</author>
  12. <year>2004</year>
  13. <price>77</price>
  14. </book>
  15. <bookid=“3”>
  16. <name>thinkthinkthink</name>
  17. <author>aaa</author>
  18. <year>1997</year>
  19. <price>100</price>
  20. </book>
  21. </bookstore>

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
    <book id="1">
        <name>冰与火之歌</name>
        <author>乔治马丁</author>
        <year>2014</year>
        <price>89</price>
    </book>
    <book id="2">
        <name>安徒生童话</name>
        <author>安徒生</author>
        <year>2004</year>
        <price>77</price>
    </book>
    <book id="3">
        <name>think think think</name>
        <author>aaa</author>
        <year>1997</year>
        <price>100</price>
    </book>
</bookstore>
bean类:Book.java

[java] view plain copy print?

  1. publicclassBook{
  2. /**
  3. *@authorlune
  4. */
  5. privateintid;
  6. privateStringname;
  7. privateStringauthor;
  8. privateintyear;
  9. privatedoubleprice;
  10. /**
  11. *@returntheid
  12. */
  13. publicintgetId(){
  14. returnid;
  15. }
  16. /**
  17. *@paramidtheidtoset
  18. */
  19. publicvoidsetId(intid){
  20. this.id=id;
  21. }
  22. /**
  23. *@returnthename
  24. */
  25. publicStringgetName(){
  26. returnname;
  27. }
  28. /**
  29. *@paramnamethenametoset
  30. */
  31. publicvoidsetName(Stringname){
  32. this.name=name;
  33. }
  34. /**
  35. *@returntheauthor
  36. */
  37. publicStringgetAuthor(){
  38. returnauthor;
  39. }
  40. /**
  41. *@paramauthortheauthortoset
  42. */
  43. publicvoidsetAuthor(Stringauthor){
  44. this.author=author;
  45. }
  46. /**
  47. *@returntheyear
  48. */
  49. publicintgetYear(){
  50. returnyear;
  51. }
  52. /**
  53. *@paramyeartheyeartoset
  54. */
  55. publicvoidsetYear(intyear){
  56. this.year=year;
  57. }
  58. /**
  59. *@returntheprice
  60. */
  61. publicdoublegetPrice(){
  62. returnprice;
  63. }
  64. /**
  65. *@parampricethepricetoset
  66. */
  67. publicvoidsetPrice(doubleprice){
  68. this.price=price;
  69. }
  70. @Override
  71. publicStringtoString(){
  72. return“Book[id=”+id+“,name=”+name+“,author=”+author+“,year=”+year+“,price=”+price+“]”;
  73. }
  74. }

public class Book {

    /**
     * @author lune
     */

    private int id;
    private String name;
    private String author;
    private int year;
    private double price;

    /**
     * @return the id
     */
    public int getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @return the author
     */
    public String getAuthor() {
        return author;
    }
    /**
     * @param author the author to set
     */
    public void setAuthor(String author) {
        this.author = author;
    }
    /**
     * @return the year
     */
    public int getYear() {
        return year;
    }
    /**
     * @param year the year to set
     */
    public void setYear(int year) {
        this.year = year;
    }
    /**
     * @return the price
     */
    public double getPrice() {
        return price;
    }
    /**
     * @param price the price to set
     */
    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book [id=" + id + ", name=" + name + ", author=" + author + ", year=" + year + ", price=" + price + "]";
    }

}

1.DOM方式解析XML

[java] view plain copy print?

  1. importjava.util.ArrayList;
  2. importjava.util.List;
  3. importjavax.xml.parsers.Documentbuilder;
  4. importjavax.xml.parsers.DocumentBuilderFactory;
  5. importjavax.xml.parsers.ParserconfigurationException;
  6. importorg.w3c.dom.Document;
  7. importorg.w3c.dom.NamedNodeMap;
  8. importorg.w3c.dom.NodeList;
  9. importcom.lune.bean.Book;
  10. /**
  11. *用DOM方式读取xml文件
  12. *@authorlune
  13. */
  14. publicclassReadxmlByDom{
  15. privatestaticDocumentBuilderFactorydbFactory=null;
  16. privatestaticDocumentBuilderdb=null;
  17. privatestaticDocumentdocument=null;
  18. privatestaticList<Book>books=null;
  19. static{
  20. try{
  21. dbFactory=DocumentBuilderFactory.newinstance();
  22. db=dbFactory.newDocumentBuilder();
  23. }catch(ParserConfigurationExceptione){
  24. e.printstacktrace();
  25. }
  26. }
  27. publicstaticList<Book>getBooks(StringfileName)throwsException{
  28. //将给定URI的内容解析为一个XML文档,并返回Document对象
  29. document=db.parse(fileName);
  30. //按文档顺序返回包含在文档中且具有给定标记名称的所有Element的NodeList
  31. NodeListbookList=document.getElementsByTagName(”book”);
  32. books=newArrayList<Book>();
  33. //遍历books
  34. for(inti=0;i<bookList.getLength();i++){
  35. Bookbook=newBook();
  36. //获取第i个book结点
  37. org.w3c.dom.Nodenode=bookList.item(i);
  38. //获取第i个book的所有属性
  39. NamedNodeMapnamedNodeMap=node.getAttributes();
  40. //获取已知名为id的属性值
  41. Stringid=namedNodeMap.getNamedItem(”id”).getTextcontent();//System.out.println(id);
  42. book.setId(integer.parseInt(id));
  43. //获取book结点的子节点,包含了Test类型的换行
  44. NodeListcList=node.getChildNodes();//System.out.println(cList.getLength());9
  45. //将一个book里面的属性加入数组
  46. ArrayList<String>contents=newArrayList<>();
  47. for(intj=1;j<cList.getLength();j+=2){
  48. org.w3c.dom.NodecNode=cList.item(j);
  49. Stringcontent=cNode.getFirstChild().getTextContent();
  50. contents.add(content);
  51. //System.out.println(contents);
  52. }
  53. book.setName(contents.get(0));
  54. book.setAuthor(contents.get(1));
  55. book.setYear(Integer.parseInt(contents.get(2)));
  56. book.setPrice(Double.parseDouble(contents.get(3)));
  57. books.add(book);
  58. }
  59. returnbooks;
  60. }
  61. publicstaticvoidmain(Stringargs[]){
  62. StringfileName=”src/res/books.xml”;
  63. try{
  64. List<Book>list=ReadxmlByDom.getBooks(fileName);
  65. for(Bookbook:list){
  66. System.out.println(book);
  67. }
  68. }catch(Exceptione){
  69. //TODOAuto-generatedcatchblock
  70. e.printStackTrace();
  71. }
  72. }
  73. }

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.NamedNodeMap;
import org.w3c.dom.NodeList;

import com.lune.bean.Book;

/**
 * 用DOM方式读取xml文件
 * @author lune
 */
public class ReadxmlByDom {
    private static DocumentBuilderFactory dbFactory = null;
    private static DocumentBuilder db = null;
    private static Document document = null;
    private static List<Book> books = null;
    static{
        try {
            dbFactory = DocumentBuilderFactory.newInstance();
            db = dbFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }

    public static List<Book> getBooks(String fileName) throws Exception{
        //将给定 URI 的内容解析为一个 XML 文档,并返回Document对象
        document = db.parse(fileName);
        //按文档顺序返回包含在文档中且具有给定标记名称的所有 Element 的 NodeList
        NodeList bookList = document.getElementsByTagName("book");
        books = new ArrayList<Book>();
        //遍历books
        for(int i=0;i<bookList.getLength();i++){
            Book book = new Book();
            //获取第i个book结点
            org.w3c.dom.Node node = bookList.item(i);
            //获取第i个book的所有属性
            NamedNodeMap namedNodeMap = node.getAttributes();
            //获取已知名为id的属性值
            String id = namedNodeMap.getNamedItem("id").getTextContent();//System.out.println(id);
            book.setId(Integer.parseInt(id));

            //获取book结点的子节点,包含了Test类型的换行
            NodeList cList = node.getChildNodes();//System.out.println(cList.getLength());9

            //将一个book里面的属性加入数组
            ArrayList<String> contents = new ArrayList<>();
            for(int j=1;j<cList.getLength();j+=2){

                org.w3c.dom.Node cNode = cList.item(j);
                String content = cNode.getFirstChild().getTextContent();
                contents.add(content);
                //System.out.println(contents);
            }

            book.setName(contents.get(0));
            book.setAuthor(contents.get(1));
            book.setYear(Integer.parseInt(contents.get(2)));
            book.setPrice(Double.parseDouble(contents.get(3)));
            books.add(book);
        }

        return books;

    }

    public static void main(String args[]){
        String fileName = "src/res/books.xml";
        try {
            List<Book> list = ReadxmlByDom.getBooks(fileName);
            for(Book book :list){
                System.out.println(book);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

2.SAX方式解析XML

需要自定义Defaulthandler处理器

[java] view plain copy print?

  1. importjava.util.ArrayList;
  2. importjava.util.List;
  3. importorg.xml.sax.Attributes;
  4. importorg.xml.sax.SAXException;
  5. importorg.xml.sax.helpers.DefaultHandler;
  6. importcom.lune.bean.Book;
  7. /**
  8. *用SAX解析xml文件时需要的handler
  9. *@authorlune
  10. */
  11. publicclassSAXParseHandlerextendsDefaultHandler{
  12. privateList<Book>list;//存放解析到的book数组
  13. privateBookbook;//存放当前解析的book
  14. privateStringcontent=null;//存放当前节点值
  15. /**
  16. *开始解析xml文档时调用此方法
  17. */
  18. @Override
  19. publicvoidstartDocument()throwsSAXException{
  20. super.startDocument();
  21. System.out.println(”开始解析xml文件”);
  22. list=newArrayList<Book>();
  23. }
  24. /**
  25. *文档解析完成后调用此方法
  26. */
  27. @Override
  28. publicvoidendDocument()throwsSAXException{
  29. super.endDocument();
  30. System.out.println(”xml文件解析完毕”);
  31. }
  32. /**
  33. *开始解析节点时调用此方法
  34. */
  35. @Override
  36. publicvoidstartElement(Stringuri,StringlocalName,StringqName,Attributesattributes)throwsSAXException{
  37. super.startElement(uri,localName,qName,attributes);
  38. //当节点名为book时,获取book的属性id
  39. if(qName.equals(“book”)){
  40. book=newBook();
  41. Stringid=attributes.getValue(”id”);//System.out.println(“id值为”+id);
  42. book.setId(Integer.parseInt(id));
  43. }
  44. }
  45. /**
  46. *节点解析完毕时调用此方法
  47. *
  48. *@paramqName节点名
  49. */
  50. @Override
  51. publicvoidendElement(Stringuri,StringlocalName,StringqName)throwsSAXException{
  52. super.endElement(uri,localName,qName);
  53. if(qName.equals(“name”)){
  54. book.setName(content);
  55. //System.out.println(“书名”+content);
  56. }elseif(qName.equals(“author”)){
  57. book.setAuthor(content);
  58. //System.out.println(“作者”+content);
  59. }elseif(qName.equals(“year”)){
  60. book.setYear(Integer.parseInt(content));
  61. //System.out.println(“年份”+content);
  62. }elseif(qName.equals(“price”)){
  63. book.setPrice(Double.parseDouble(content));
  64. //System.out.println(“价格”+content);
  65. }elseif(qName.equals(“book”)){//当结束当前book解析时,将该book添加到数组后置为空,方便下一次book赋值
  66. list.add(book);
  67. book=null;
  68. }
  69. }
  70. /**
  71. *此方法用来获取节点的值
  72. */
  73. @Override
  74. publicvoidcharacters(char[]ch,intstart,intlength)throwsSAXException{
  75. super.characters(ch,start,length);
  76. content=newString(ch,start,length);
  77. //收集不为空白的节点值
  78. //if(!content.trim().equals(“”)){
  79. //System.out.println(“节点值为:”+content);
  80. //}
  81. }
  82. publicList<Book>getBooks(){
  83. returnlist;
  84. }
  85. }

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.lune.bean.Book;

/**
 * 用SAX解析xml文件时需要的handler
 * @author lune
 */
public class SAXParseHandler extends DefaultHandler {
    private List<Book> list;         //存放解析到的book数组
    private Book book;               //存放当前解析的book

    private String content = null;   //存放当前节点值

    /**
     * 开始解析xml文档时调用此方法
     */
    @Override
    public void startDocument() throws SAXException {

        super.startDocument();
        System.out.println("开始解析xml文件");
        list = new ArrayList<Book>();
    }



    /** 
     * 文档解析完成后调用此方法
     */
    @Override
    public void endDocument() throws SAXException {

        super.endDocument();
        System.out.println("xml文件解析完毕");
    }



    /**
     * 开始解析节点时调用此方法
     */
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

        super.startElement(uri, localName, qName, attributes);

        //当节点名为book时,获取book的属性id
        if(qName.equals("book")){
            book = new Book();
            String id = attributes.getValue("id");//System.out.println("id值为"+id);
            book.setId(Integer.parseInt(id));
        }

    }


    /**
     *节点解析完毕时调用此方法
     *
     *@param qName 节点名
     */
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {

        super.endElement(uri, localName, qName);
        if(qName.equals("name")){
            book.setName(content);
            //System.out.println("书名"+content);
        }else if(qName.equals("author")){
            book.setAuthor(content);
        //  System.out.println("作者"+content);
        }else if(qName.equals("year")){
            book.setYear(Integer.parseInt(content));
        //  System.out.println("年份"+content);
        }else if(qName.equals("price")){
            book.setPrice(Double.parseDouble(content));
        //  System.out.println("价格"+content);
        }else if(qName.equals("book")){         //当结束当前book解析时,将该book添加到数组后置为空,方便下一次book赋值
            list.add(book);
            book = null;
        }   

    }



    /** 
     * 此方法用来获取节点的值
     */
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {

        super.characters(ch, start, length);

        content = new String(ch, start, length);
        //收集不为空白的节点值
//      if(!content.trim().equals("")){
//          System.out.println("节点值为:"+content);
//      }

    }

    public List<Book> getBooks(){
        return list;
    }

}

[java] view plain copy print?

  1. importjava.io.IOException;
  2. importjava.util.List;
  3. importjavax.xml.parsers.ParserConfigurationException;
  4. importjavax.xml.parsers.SAXParser;
  5. importjavax.xml.parsers.SAXParserFactory;
  6. importorg.xml.sax.SAXException;
  7. importorg.xml.sax.helpers.ParserFactory;
  8. importcom.lune.bean.Book;
  9. importcom.lune.handler.SAXParseHandler;
  10. /**
  11. *用SAX方式读取xml文件
  12. *@authorlune
  13. */
  14. publicclassReadXmlBySAX{
  15. privatestaticList<Book>books=null;
  16. privateSAXParserFactorysParserFactory=null;
  17. privateSAXParserparser=null;
  18. publicList<Book>getBooks(StringfileName)throwsException{
  19. SAXParserFactorysParserFactory=SAXParserFactory.newInstance();
  20. SAXParserparser=sParserFactory.newSAXParser();
  21. SAXParseHandlerhandler=newSAXParseHandler();
  22. parser.parse(fileName,handler);
  23. returnhandler.getBooks();
  24. }
  25. /**
  26. *@paramargs
  27. */
  28. publicstaticvoidmain(String[]args){
  29. try{
  30. books=newReadXmlBySAX().getBooks(“src/res/books.xml”);
  31. for(Bookbook:books){
  32. System.out.println(book);
  33. }
  34. }catch(Exceptione){
  35. e.printStackTrace();
  36. }
  37. }
  38. }

import java.io.IOException;
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 org.xml.sax.helpers.ParserFactory;

import com.lune.bean.Book;
import com.lune.handler.SAXParseHandler;

/**
 * 用SAX方式读取xml文件
 * @author lune
 */
public class ReadXmlBySAX {

    private static List<Book> books = null;

    private  SAXParserFactory sParserFactory = null;
    private  SAXParser parser = null;


    public List<Book> getBooks(String fileName) throws Exception{
        SAXParserFactory sParserFactory = SAXParserFactory.newInstance();
        SAXParser parser = sParserFactory.newSAXParser();

        SAXParseHandler handler = new SAXParseHandler();
        parser.parse(fileName, handler);

        return handler.getBooks();

    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            books = new ReadXmlBySAX().getBooks("src/res/books.xml");
            for(Book book:books){
                System.out.println(book);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
3.JDOM方式解析XML

[java] view plain copy print?

  1. importjava.io.fileinputstream;
  2. importjava.io.filenotfoundException;
  3. importjava.io.IOException;
  4. importjava.util.ArrayList;
  5. importjava.util.List;
  6. importorg.jdom2.JDOMException;
  7. importorg.jdom2.input.SAXBuilder;
  8. importcom.lune.bean.Book;
  9. importorg.jdom2.*;
  10. /**
  11. *用JDOM方式读取xml文件
  12. *@authorlune
  13. */
  14. publicclassReadXMLByJDom{
  15. privateList<Book>books=null;
  16. privateBookbook=null;
  17. publicList<Book>getBooks(StringfileName){
  18. SAXBuildersaxBuilder=newSAXBuilder();
  19. try{
  20. Documentdocument=saxBuilder.build(newFileInputStream(fileName));
  21. //获取根节点bookstore
  22. ElementrootElement=document.getRootElement();
  23. //获取根节点的子节点,返回子节点的数组
  24. List<Element>bookList=rootElement.getchildren();
  25. books=newArrayList<Book>();
  26. for(ElementbookElement:bookList){
  27. book=newBook();
  28. //获取bookElement的属性
  29. List<Attribute>bookAttributes=bookElement.getAttributes();
  30. for(Attributeattribute:bookAttributes){
  31. if(attribute.getName().equals(“id”)){
  32. Stringid=attribute.getValue();//System.out.println(id);
  33. book.setId(Integer.parseInt(id));
  34. }
  35. }
  36. //获取bookElement的子节点
  37. List<Element>children=bookElement.getChildren();
  38. for(Elementchild:children){
  39. if(child.getName().equals(“name”)){
  40. Stringname=child.getValue();//System.out.println(name);
  41. book.setName(name);
  42. }elseif(child.getName().equals(“author”)){
  43. Stringauthor=child.getValue();
  44. book.setAuthor(author);//System.out.println(author);
  45. }elseif(child.getName().equals(“year”)){
  46. Stringyear=child.getValue();
  47. book.setYear(Integer.parseInt(year));
  48. }elseif(child.getName().equals(“price”)){
  49. Stringprice=child.getValue();
  50. book.setPrice(Double.parseDouble(price));
  51. }
  52. }
  53. books.add(book);
  54. book=null;
  55. }
  56. }catch(FileNotFoundExceptione){
  57. e.printStackTrace();
  58. }catch(JDOMExceptione){
  59. e.printStackTrace();
  60. }catch(IOExceptione){
  61. e.printStackTrace();
  62. }
  63. returnbooks;
  64. }
  65. publicstaticvoidmain(String[]args){
  66. //TODOAuto-generatedmethodstub
  67. StringfileName=”src/res/books.xml”;
  68. List<Book>books=newReadXMLByJDom().getBooks(fileName);
  69. for(Bookbook:books){
  70. System.out.println(book);
  71. }
  72. }
  73. }

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import com.lune.bean.Book;

import org.jdom2.*;

/**
 * 用JDOM方式读取xml文件
 * @author lune
 */
public class ReadXMLByJDom {

    private List<Book> books = null;
    private Book book = null;

    public List<Book> getBooks(String fileName){
        SAXBuilder saxBuilder = new SAXBuilder();
        try {
            Document document = saxBuilder.build(new FileInputStream(fileName));
            //获取根节点bookstore
            Element rootElement = document.getRootElement();
            //获取根节点的子节点,返回子节点的数组
            List<Element> bookList = rootElement.getChildren();
            books = new ArrayList<Book>();
            for(Element bookElement : bookList){
                book = new Book();
                //获取bookElement的属性
                List<Attribute> bookAttributes = bookElement.getAttributes();
                for(Attribute attribute : bookAttributes){
                    if(attribute.getName().equals("id")){
                        String id = attribute.getValue(); //System.out.println(id);
                        book.setId(Integer.parseInt(id));
                    }
                }
                //获取bookElement的子节点
                List<Element> children = bookElement.getChildren();
                for(Element child : children){
                    if(child.getName().equals("name")){
                        String name = child.getValue();//System.out.println(name);
                        book.setName(name);
                    }else if(child.getName().equals("author")){
                        String author = child.getValue();
                        book.setAuthor(author);//System.out.println(author);
                    }else if(child.getName().equals("year")){
                        String year = child.getValue();
                        book.setYear(Integer.parseInt(year));
                    }else if(child.getName().equals("price")){
                        String price = child.getValue();
                        book.setPrice(Double.parseDouble(price));
                    }

                }

                books.add(book);
                book = null;

            }

        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (JDOMException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }

        return books;

    }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String fileName = "src/res/books.xml";
        List<Book> books= new ReadXMLByJDom().getBooks(fileName);
        for(Book book : books){
            System.out.println(book);
        }
    }

}

4.DOM4j方式解析XML

[java] view plain copy print?

  1. importjava.io.File;
  2. importjava.util.ArrayList;
  3. importjava.util.Iterator;
  4. importjava.util.List;
  5. importorg.dom4j.Attribute;
  6. importorg.dom4j.Document;
  7. importorg.dom4j.DocumentException;
  8. importorg.dom4j.Element;
  9. importorg.dom4j.io.SAXReader;
  10. importcom.lune.bean.Book;
  11. /**
  12. *用DOM4J方法读取xml文件
  13. *@authorlune
  14. */
  15. publicclassReadXMLByDom4j{
  16. privateList<Book>bookList=null;
  17. privateBookbook=null;
  18. publicList<Book>getBooks(Filefile){
  19. SAXReaderreader=newSAXReader();
  20. try{
  21. Documentdocument=reader.read(file);
  22. Elementbookstore=document.getRootElement();
  23. Iteratorstoreit=bookstore.elementIterator();
  24. bookList=newArrayList<Book>();
  25. while(storeit.hasNext()){
  26. book=newBook();
  27. ElementbookElement=(Element)storeit.next();
  28. //遍历bookElement的属性
  29. List<Attribute>attributes=bookElement.attributes();
  30. for(Attributeattribute:attributes){
  31. if(attribute.getName().equals(“id”)){
  32. Stringid=attribute.getValue();//System.out.println(id);
  33. book.setId(Integer.parseInt(id));
  34. }
  35. }
  36. Iteratorbookit=bookElement.elementIterator();
  37. while(bookit.hasNext()){
  38. Elementchild=(Element)bookit.next();
  39. StringnodeName=child.getName();
  40. if(nodeName.equals(“name”)){
  41. //System.out.println(child.getStringValue());
  42. Stringname=child.getStringValue();
  43. book.setName(name);
  44. }elseif(nodeName.equals(“author”)){
  45. Stringauthor=child.getStringValue();
  46. book.setAuthor(author);
  47. }elseif(nodeName.equals(“year”)){
  48. Stringyear=child.getStringValue();
  49. book.setYear(Integer.parseInt(year));
  50. }elseif(nodeName.equals(“price”)){
  51. Stringprice=child.getStringValue();
  52. book.setPrice(Double.parseDouble(price));
  53. }
  54. }
  55. bookList.add(book);
  56. book=null;
  57. }
  58. }catch(DocumentExceptione){
  59. e.printStackTrace();
  60. }
  61. returnbookList;
  62. }
  63. /**
  64. *@paramargs
  65. */
  66. publicstaticvoidmain(String[]args){
  67. //TODOAuto-generatedmethodstub
  68. Filefile=newFile(“src/res/books.xml”);
  69. List<Book>bookList=newReadXMLByDom4j().getBooks(file);
  70. for(Bookbook:bookList){
  71. System.out.println(book);
  72. }
  73. }
  74. }

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.lune.bean.Book;

/**
 * 用DOM4J方法读取xml文件
 * @author lune
 */
public class ReadXMLByDom4j {

    private List<Book> bookList = null;
    private Book book = null;

    public List<Book> getBooks(File file){

        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(file);
            Element bookstore = document.getRootElement();
            Iterator storeit = bookstore.elementIterator();

            bookList = new ArrayList<Book>();
            while(storeit.hasNext()){

                book = new Book();
                Element bookElement = (Element) storeit.next();
                //遍历bookElement的属性
                List<Attribute> attributes = bookElement.attributes();
                for(Attribute attribute : attributes){
                    if(attribute.getName().equals("id")){
                        String id = attribute.getValue();//System.out.println(id);
                        book.setId(Integer.parseInt(id));
                    }
                }

                Iterator bookit = bookElement.elementIterator();
                while(bookit.hasNext()){
                    Element child = (Element) bookit.next();
                    String nodeName = child.getName();
                    if(nodeName.equals("name")){
                        //System.out.println(child.getStringValue());
                        String name = child.getStringValue();
                        book.setName(name);
                    }else if(nodeName.equals("author")){
                        String author = child.getStringValue();
                        book.setAuthor(author);
                    }else if(nodeName.equals("year")){
                        String year = child.getStringValue();
                        book.setYear(Integer.parseInt(year));
                    }else if(nodeName.equals("price")){
                        String price = child.getStringValue();
                        book.setPrice(Double.parseDouble(price));
                    }
                }
                bookList.add(book);
                book = null;

            }
        } catch (DocumentException e) {

            e.printStackTrace();
        }


        return bookList;

    }


    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        File file = new File("src/res/books.xml");
        List<Book> bookList = new ReadXMLByDom4j().getBooks(file);
        for(Book book : bookList){
            System.out.println(book);
        }
    }

}

其中后两者需要导入外部jar包.

文章中的源码可在下面地址下载:

http://github.com/clemontine/XMLParser

相关阅读

搜索引擎工作原理解析

本篇文章从整个搜索引擎架构技术大框架方面来学习,搜索引擎工作原理。 1 搜索引擎基本模块 2 爬虫 网络爬虫(Web crawler),是

Java常见面试题

今天整理了下面试中会经常出现的一些问题。 1.线程的几种状态和相互的转换? 回答要点: 1)线程有5中状态,分别是: 创建 就绪 运行 阻塞

Effective Java 第 3 版(中文版)PDF 下载

微信公众号:一个优秀的废人如有问题或建议,请后台留言,我会尽力解决你的问题。 简介 本书一共包含 90 个条目,每个条目讨论 Java 程序

java中方法的重载及注意事项

/* 方法的重载特性(overload) 在同一个类中,允许出现同名的方法,只要方法的参数列表不同即可,这就是方法的重载 参数列表不同:参数个数

Java读取ZIP文件ZipEntry.getsize()总是返回-1?

解决方法(Code)在文章最后面,耐心看完 今天在项目中遇到一个问题,有一个需求是需要验证下载的ZIP文件,解压读取ZIP文件夹内部的文件,文

分享到:

栏目导航

推荐阅读

热门阅读