zoukankan      html  css  js  c++  java
  • Java解析XML文件

    转:

    Java解析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

    1. <?xml version=“1.0” encoding=“UTF-8”?>  
    2. <bookstore>  
    3.     <book id=“1”>  
    4.         <name>冰与火之歌</name>  
    5.         <author>乔治马丁</author>  
    6.         <year>2014</year>  
    7.         <price>89</price>  
    8.     </book>  
    9.     <book id=“2”>  
    10.         <name>安徒生童话</name>  
    11.         <author>安徒生</author>  
    12.         <year>2004</year>  
    13.         <price>77</price>  
    14.     </book>  
    15.     <book id=“3”>  
    16.         <name>think think think</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>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    bean类:Book.java

    1. public class Book {  
    2.       
    3.     /** 
    4.      * @author lune 
    5.      */  
    6.       
    7.     private int id;  
    8.     private String name;  
    9.     private String author;  
    10.     private int year;  
    11.     private double price;  
    12.       
    13.     /** 
    14.      * @return the id 
    15.      */  
    16.     public int getId() {  
    17.         return id;  
    18.     }  
    19.     /** 
    20.      * @param id the id to set 
    21.      */  
    22.     public void setId(int id) {  
    23.         this.id = id;  
    24.     }  
    25.     /** 
    26.      * @return the name 
    27.      */  
    28.     public String getName() {  
    29.         return name;  
    30.     }  
    31.     /** 
    32.      * @param name the name to set 
    33.      */  
    34.     public void setName(String name) {  
    35.         this.name = name;  
    36.     }  
    37.     /** 
    38.      * @return the author 
    39.      */  
    40.     public String getAuthor() {  
    41.         return author;  
    42.     }  
    43.     /** 
    44.      * @param author the author to set 
    45.      */  
    46.     public void setAuthor(String author) {  
    47.         this.author = author;  
    48.     }  
    49.     /** 
    50.      * @return the year 
    51.      */  
    52.     public int getYear() {  
    53.         return year;  
    54.     }  
    55.     /** 
    56.      * @param year the year to set 
    57.      */  
    58.     public void setYear(int year) {  
    59.         this.year = year;  
    60.     }  
    61.     /** 
    62.      * @return the price 
    63.      */  
    64.     public double getPrice() {  
    65.         return price;  
    66.     }  
    67.     /** 
    68.      * @param price the price to set 
    69.      */  
    70.     public void setPrice(double price) {  
    71.         this.price = price;  
    72.     }  
    73.       
    74.     @Override  
    75.     public String toString() {  
    76.         return “Book [id=” + id + “, name=” + name + “, author=” + author + “, year=” + year + “, price=” + price + “]”;  
    77.     }  
    78.           
    79. }  
    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79


    1.DOM方式解析XML

    1. import java.util.ArrayList;  
    2. import java.util.List;  
    3.   
    4. import javax.xml.parsers.DocumentBuilder;  
    5. import javax.xml.parsers.DocumentBuilderFactory;  
    6. import javax.xml.parsers.ParserConfigurationException;  
    7.   
    8. import org.w3c.dom.Document;  
    9. import org.w3c.dom.NamedNodeMap;  
    10. import org.w3c.dom.NodeList;  
    11.   
    12. import com.lune.bean.Book;  
    13.   
    14. /** 
    15.  * 用DOM方式读取xml文件 
    16.  * @author lune 
    17.  */  
    18. public class ReadxmlByDom {  
    19.     private static DocumentBuilderFactory dbFactory = null;  
    20.     private static DocumentBuilder db = null;  
    21.     private static Document document = null;  
    22.     private static List<Book> books = null;  
    23.     static{  
    24.         try {  
    25.             dbFactory = DocumentBuilderFactory.newInstance();  
    26.             db = dbFactory.newDocumentBuilder();  
    27.         } catch (ParserConfigurationException e) {  
    28.             e.printStackTrace();  
    29.         }  
    30.     }  
    31.       
    32.     public static List<Book> getBooks(String fileName) throws Exception{  
    33.         //将给定 URI 的内容解析为一个 XML 文档,并返回Document对象  
    34.         document = db.parse(fileName);  
    35.         //按文档顺序返回包含在文档中且具有给定标记名称的所有 Element 的 NodeList  
    36.         NodeList bookList = document.getElementsByTagName(”book”);  
    37.         books = new ArrayList<Book>();  
    38.         //遍历books  
    39.         for(int i=0;i<bookList.getLength();i++){  
    40.             Book book = new Book();  
    41.             //获取第i个book结点  
    42.             org.w3c.dom.Node node = bookList.item(i);  
    43.             //获取第i个book的所有属性  
    44.             NamedNodeMap namedNodeMap = node.getAttributes();  
    45.             //获取已知名为id的属性值  
    46.             String id = namedNodeMap.getNamedItem(”id”).getTextContent();//System.out.println(id);  
    47.             book.setId(Integer.parseInt(id));  
    48.               
    49.             //获取book结点的子节点,包含了Test类型的换行  
    50.             NodeList cList = node.getChildNodes();//System.out.println(cList.getLength());9  
    51.               
    52.             //将一个book里面的属性加入数组  
    53.             ArrayList<String> contents = new ArrayList<>();  
    54.             for(int j=1;j<cList.getLength();j+=2){  
    55.                   
    56.                 org.w3c.dom.Node cNode = cList.item(j);  
    57.                 String content = cNode.getFirstChild().getTextContent();  
    58.                 contents.add(content);  
    59.                 //System.out.println(contents);  
    60.             }  
    61.               
    62.             book.setName(contents.get(0));  
    63.             book.setAuthor(contents.get(1));  
    64.             book.setYear(Integer.parseInt(contents.get(2)));  
    65.             book.setPrice(Double.parseDouble(contents.get(3)));  
    66.             books.add(book);  
    67.         }  
    68.           
    69.         return books;  
    70.           
    71.     }  
    72.       
    73.     public static void main(String args[]){  
    74.         String fileName = ”src/res/books.xml”;  
    75.         try {  
    76.             List<Book> list = ReadxmlByDom.getBooks(fileName);  
    77.             for(Book book :list){  
    78.                 System.out.println(book);  
    79.             }  
    80.         } catch (Exception e) {  
    81.             // TODO Auto-generated catch block  
    82.             e.printStackTrace();  
    83.         }  
    84.     }  
    85.           
    86. }  
    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();
            }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86



    2.SAX方式解析XML
    需要自定义DefaultHandler处理器

    1. import java.util.ArrayList;  
    2. import java.util.List;  
    3.   
    4. import org.xml.sax.Attributes;  
    5. import org.xml.sax.SAXException;  
    6. import org.xml.sax.helpers.DefaultHandler;  
    7.   
    8. import com.lune.bean.Book;  
    9.   
    10. /** 
    11.  * 用SAX解析xml文件时需要的handler 
    12.  * @author lune 
    13.  */  
    14. public class SAXParseHandler extends DefaultHandler {  
    15.     private List<Book> list;         //存放解析到的book数组  
    16.     private Book book;               //存放当前解析的book  
    17.       
    18.     private String content = null;   //存放当前节点值  
    19.       
    20.     /** 
    21.      * 开始解析xml文档时调用此方法 
    22.      */  
    23.     @Override  
    24.     public void startDocument() throws SAXException {  
    25.           
    26.         super.startDocument();  
    27.         System.out.println(”开始解析xml文件”);  
    28.         list = new ArrayList<Book>();  
    29.     }  
    30.   
    31.   
    32.   
    33.     /**  
    34.      * 文档解析完成后调用此方法 
    35.      */  
    36.     @Override  
    37.     public void endDocument() throws SAXException {  
    38.           
    39.         super.endDocument();  
    40.         System.out.println(”xml文件解析完毕”);  
    41.     }  
    42.   
    43.   
    44.   
    45.     /** 
    46.      * 开始解析节点时调用此方法 
    47.      */  
    48.     @Override  
    49.     public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {  
    50.           
    51.         super.startElement(uri, localName, qName, attributes);  
    52.           
    53.         //当节点名为book时,获取book的属性id  
    54.         if(qName.equals(“book”)){  
    55.             book = new Book();  
    56.             String id = attributes.getValue(”id”);//System.out.println(“id值为”+id);  
    57.             book.setId(Integer.parseInt(id));  
    58.         }  
    59.           
    60.     }  
    61.   
    62.   
    63.     /** 
    64.      *节点解析完毕时调用此方法 
    65.      * 
    66.      *@param qName 节点名 
    67.      */  
    68.     @Override  
    69.     public void endElement(String uri, String localName, String qName) throws SAXException {  
    70.           
    71.         super.endElement(uri, localName, qName);  
    72.         if(qName.equals(“name”)){  
    73.             book.setName(content);  
    74.             //System.out.println(“书名”+content);  
    75.         }else if(qName.equals(“author”)){  
    76.             book.setAuthor(content);  
    77.         //  System.out.println(“作者”+content);  
    78.         }else if(qName.equals(“year”)){  
    79.             book.setYear(Integer.parseInt(content));  
    80.         //  System.out.println(“年份”+content);  
    81.         }else if(qName.equals(“price”)){  
    82.             book.setPrice(Double.parseDouble(content));  
    83.         //  System.out.println(“价格”+content);  
    84.         }else if(qName.equals(“book”)){         //当结束当前book解析时,将该book添加到数组后置为空,方便下一次book赋值  
    85.             list.add(book);  
    86.             book = null;  
    87.         }     
    88.           
    89.     }  
    90.   
    91.   
    92.   
    93.     /**  
    94.      * 此方法用来获取节点的值 
    95.      */  
    96.     @Override  
    97.     public void characters(char[] ch, int start, int length) throws SAXException {  
    98.           
    99.         super.characters(ch, start, length);  
    100.           
    101.         content = new String(ch, start, length);  
    102.         //收集不为空白的节点值  
    103. //      if(!content.trim().equals(“”)){  
    104. //          System.out.println(“节点值为:”+content);  
    105. //      }  
    106.           
    107.     }  
    108.   
    109.     public List<Book> getBooks(){  
    110.         return list;  
    111.     }  
    112.       
    113. }  
    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;
        }
    
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112


    1. import java.io.IOException;  
    2. import java.util.List;  
    3.   
    4. import javax.xml.parsers.ParserConfigurationException;  
    5. import javax.xml.parsers.SAXParser;  
    6. import javax.xml.parsers.SAXParserFactory;  
    7.   
    8. import org.xml.sax.SAXException;  
    9. import org.xml.sax.helpers.ParserFactory;  
    10.   
    11. import com.lune.bean.Book;  
    12. import com.lune.handler.SAXParseHandler;  
    13.   
    14. /** 
    15.  * 用SAX方式读取xml文件 
    16.  * @author lune 
    17.  */  
    18. public class ReadXmlBySAX {  
    19.   
    20.     private static List<Book> books = null;  
    21.       
    22.     private  SAXParserFactory sParserFactory = null;  
    23.     private  SAXParser parser = null;  
    24.       
    25.       
    26.     public List<Book> getBooks(String fileName) throws Exception{  
    27.         SAXParserFactory sParserFactory = SAXParserFactory.newInstance();  
    28.         SAXParser parser = sParserFactory.newSAXParser();  
    29.           
    30.         SAXParseHandler handler = new SAXParseHandler();  
    31.         parser.parse(fileName, handler);  
    32.           
    33.         return handler.getBooks();  
    34.           
    35.     }  
    36.     /** 
    37.      * @param args 
    38.      */  
    39.     public static void main(String[] args) {  
    40.         try {  
    41.             books = new ReadXmlBySAX().getBooks(“src/res/books.xml”);  
    42.             for(Book book:books){  
    43.                 System.out.println(book);  
    44.             }  
    45.               
    46.         } catch (Exception e) {  
    47.             e.printStackTrace();  
    48.         }  
    49.   
    50.     }  
    51.   
    52. }  
    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();
            }
    
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    3.JDOM方式解析XML

    1. import java.io.FileInputStream;  
    2. import java.io.FileNotFoundException;  
    3. import java.io.IOException;  
    4. import java.util.ArrayList;  
    5. import java.util.List;  
    6.   
    7. import org.jdom2.JDOMException;  
    8. import org.jdom2.input.SAXBuilder;  
    9.   
    10. import com.lune.bean.Book;  
    11.   
    12. import org.jdom2.*;  
    13.   
    14. /** 
    15.  * 用JDOM方式读取xml文件 
    16.  * @author lune 
    17.  */  
    18. public class ReadXMLByJDom {  
    19.       
    20.     private List<Book> books = null;  
    21.     private Book book = null;  
    22.       
    23.     public List<Book> getBooks(String fileName){  
    24.         SAXBuilder saxBuilder = new SAXBuilder();  
    25.         try {  
    26.             Document document = saxBuilder.build(new FileInputStream(fileName));  
    27.             //获取根节点bookstore  
    28.             Element rootElement = document.getRootElement();  
    29.             //获取根节点的子节点,返回子节点的数组  
    30.             List<Element> bookList = rootElement.getChildren();  
    31.             books = new ArrayList<Book>();  
    32.             for(Element bookElement : bookList){  
    33.                 book = new Book();  
    34.                 //获取bookElement的属性  
    35.                 List<Attribute> bookAttributes = bookElement.getAttributes();  
    36.                 for(Attribute attribute : bookAttributes){  
    37.                     if(attribute.getName().equals(“id”)){  
    38.                         String id = attribute.getValue(); //System.out.println(id);  
    39.                         book.setId(Integer.parseInt(id));  
    40.                     }  
    41.                 }  
    42.                 //获取bookElement的子节点  
    43.                 List<Element> children = bookElement.getChildren();  
    44.                 for(Element child : children){  
    45.                     if(child.getName().equals(“name”)){  
    46.                         String name = child.getValue();//System.out.println(name);  
    47.                         book.setName(name);  
    48.                     }else if(child.getName().equals(“author”)){  
    49.                         String author = child.getValue();  
    50.                         book.setAuthor(author);//System.out.println(author);  
    51.                     }else if(child.getName().equals(“year”)){  
    52.                         String year = child.getValue();  
    53.                         book.setYear(Integer.parseInt(year));  
    54.                     }else if(child.getName().equals(“price”)){  
    55.                         String price = child.getValue();  
    56.                         book.setPrice(Double.parseDouble(price));  
    57.                     }  
    58.                       
    59.                 }  
    60.                   
    61.                 books.add(book);  
    62.                 book = null;  
    63.                   
    64.             }  
    65.               
    66.         } catch (FileNotFoundException e) {  
    67.               
    68.             e.printStackTrace();  
    69.         } catch (JDOMException e) {  
    70.               
    71.             e.printStackTrace();  
    72.         } catch (IOException e) {  
    73.               
    74.             e.printStackTrace();  
    75.         }  
    76.           
    77.         return books;  
    78.           
    79.     }  
    80.   
    81.       
    82.     public static void main(String[] args) {  
    83.         // TODO Auto-generated method stub  
    84.         String fileName = ”src/res/books.xml”;  
    85.         List<Book> books= new ReadXMLByJDom().getBooks(fileName);  
    86.         for(Book book : books){  
    87.             System.out.println(book);  
    88.         }  
    89.     }  
    90.   
    91. }  
    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);
            }
        }
    
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90


    4.DOM4j方式解析XML

    1. import java.io.File;  
    2. import java.util.ArrayList;  
    3. import java.util.Iterator;  
    4. import java.util.List;  
    5.   
    6. import org.dom4j.Attribute;  
    7. import org.dom4j.Document;  
    8. import org.dom4j.DocumentException;  
    9. import org.dom4j.Element;  
    10. import org.dom4j.io.SAXReader;  
    11.   
    12. import com.lune.bean.Book;  
    13.   
    14. /** 
    15.  * 用DOM4J方法读取xml文件 
    16.  * @author lune 
    17.  */  
    18. public class ReadXMLByDom4j {  
    19.       
    20.     private List<Book> bookList = null;  
    21.     private Book book = null;  
    22.       
    23.     public List<Book> getBooks(File file){  
    24.           
    25.         SAXReader reader = new SAXReader();  
    26.         try {  
    27.             Document document = reader.read(file);  
    28.             Element bookstore = document.getRootElement();  
    29.             Iterator storeit = bookstore.elementIterator();  
    30.               
    31.             bookList = new ArrayList<Book>();  
    32.             while(storeit.hasNext()){  
    33.                   
    34.                 book = new Book();  
    35.                 Element bookElement = (Element) storeit.next();  
    36.                 //遍历bookElement的属性  
    37.                 List<Attribute> attributes = bookElement.attributes();  
    38.                 for(Attribute attribute : attributes){  
    39.                     if(attribute.getName().equals(“id”)){  
    40.                         String id = attribute.getValue();//System.out.println(id);  
    41.                         book.setId(Integer.parseInt(id));  
    42.                     }  
    43.                 }  
    44.                   
    45.                 Iterator bookit = bookElement.elementIterator();  
    46.                 while(bookit.hasNext()){  
    47.                     Element child = (Element) bookit.next();  
    48.                     String nodeName = child.getName();  
    49.                     if(nodeName.equals(“name”)){  
    50.                         //System.out.println(child.getStringValue());  
    51.                         String name = child.getStringValue();  
    52.                         book.setName(name);  
    53.                     }else if(nodeName.equals(“author”)){  
    54.                         String author = child.getStringValue();  
    55.                         book.setAuthor(author);  
    56.                     }else if(nodeName.equals(“year”)){  
    57.                         String year = child.getStringValue();  
    58.                         book.setYear(Integer.parseInt(year));  
    59.                     }else if(nodeName.equals(“price”)){  
    60.                         String price = child.getStringValue();  
    61.                         book.setPrice(Double.parseDouble(price));  
    62.                     }  
    63.                 }  
    64.                 bookList.add(book);  
    65.                 book = null;  
    66.                   
    67.             }  
    68.         } catch (DocumentException e) {  
    69.           
    70.             e.printStackTrace();  
    71.         }  
    72.           
    73.           
    74.         return bookList;  
    75.           
    76.     }  
    77.       
    78.   
    79.     /** 
    80.      * @param args 
    81.      */  
    82.     public static void main(String[] args) {  
    83.         // TODO Auto-generated method stub  
    84.         File file = new File(“src/res/books.xml”);  
    85.         List<Book> bookList = new ReadXMLByDom4j().getBooks(file);  
    86.         for(Book book : bookList){  
    87.             System.out.println(book);  
    88.         }  
    89.     }  
    90.   
    91. }  
    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);
            }
        }
    
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90


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

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

    http://github.com/clemontine/XMLParser

  • 相关阅读:
    list extend 和 append
    构建同元素的列表
    Python拷贝(深拷贝deepcopy与浅拷贝copy)
    MySQL之对数据库库表的字符集的更改
    Shell之while循环
    安装keepalived
    Zabbix监控MySQL
    Ganglia监控MySQL
    将Nagios监控信息存入Mysql
    Hadoop之回收站
  • 原文地址:https://www.cnblogs.com/libin6505/p/10119734.html
Copyright © 2011-2022 走看看