JDOM以及DOM4J方式解析XML

来源:互联网 发布:百胜ipos是什么数据库 编辑:程序博客网 时间:2024/04/19 16:45

导入jar包(jdom的jar包的下载地址:http://www.jdom.org/dist/binary):
下载之后解压会得到以下几个文件:
导入jar包1
导入jar包2
导入jar包3

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.util.List;import org.jdom2.Attribute;import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.JDOMException;import org.jdom2.input.SAXBuilder;public class JDOMTest {    public static void main(String[] args) {    // 1.创建一个SAXBuilder对象    SAXBuilder saxBuilder = new SAXBuilder();    InputStream in;    try {        // 2.创建一个输入流,将xml文件加载到输入流        in = new FileInputStream("books.xml");        // 3.通过SAXBuilder的build方法将输入流加载到SAXBuilder中        Document document = saxBuilder.build(in);        // 4.通过Document对象获取xml文件的根节点        Element rootElement = document.getRootElement();        // 5.根据根节点获取子节点的List集合        List<Element> bookList = rootElement.getChildren();        // 使用循环对bookList进行遍历        for (Element book : bookList) {        System.out.println("******** 开始解析第"            + (bookList.indexOf(book) + 1) + "本书 ********");        // 解析book的属性        // 知道节点的属性名的时候获取属性值        System.out.println("id属性" + book.getAttributeValue("id"));        // 不知道属性的个数和属性名的时候        List<Attribute> attrList = book.getAttributes();        // 遍历book的属性集合        for (Attribute attribute : attrList) {            System.out.println("属性名:" + attribute.getName() + "-属性值:"                + attribute.getValue());        }        // 对book节点的子节点的节点名和节点值进行遍历        List<Element> bookChilds = book.getChildren();        for (Element child : bookChilds) {            System.out.println("节点名:" + child.getName() + "-节点值:"                + child.getValue());        }        System.out.println("******** 结束解析第"            + (bookList.indexOf(book) + 1) + "本书 ********\n");        }    } catch (FileNotFoundException e) {        e.printStackTrace();    } catch (JDOMException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    }    }}

运行结果:
运行结果

乱码的解决

  1. 将XML文件的编码改为相应的编码;
  2. 用InputStreamReader包装Inputstream指定特定的编码。

在JDOM中存储Book对象:

创建一个Book类:

public class Book {    private String id;    private String name;    private String author;    private String year;    private String price;    private String language;    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getAuthor() {        return author;    }    public void setAuthor(String author) {        this.author = author;    }    public String getYear() {        return year;    }    public void setYear(String year) {        this.year = year;    }    public String getPrice() {        return price;    }    public void setPrice(String price) {        this.price = price;    }    public String getLanguage() {        return language;    }    public void setLanguage(String language) {        this.language = language;    }    @Override    public String toString() {        return "Book [id=" + id + ", name=" + name + ", author=" + author + ", year=" + year + ", price=" + price + ", language=" + language + "]";    }}

存储Book对象:

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import org.jdom2.Attribute;import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.JDOMException;import org.jdom2.input.SAXBuilder;public class JDOMTest {    private static ArrayList<Book> booksList = new ArrayList<Book>();    public static void main(String[] args) {    // 1.创建一个SAXBuilder对象    SAXBuilder saxBuilder = new SAXBuilder();    InputStream in;    try {        // 2.创建一个输入流,将xml文件加载到输入流        in = new FileInputStream("books.xml");        // 3.通过SAXBuilder的build方法将输入流加载到SAXBuilder中        Document document = saxBuilder.build(in);        // 4.通过Document对象获取xml文件的根节点        Element rootElement = document.getRootElement();        // 5.根据根节点获取子节点的List集合        List<Element> bookList = rootElement.getChildren();        // 使用循环对bookList进行遍历        for (Element book : bookList) {        Book bookEntity = new Book();        System.out.println("******** 开始解析第"            + (bookList.indexOf(book) + 1) + "本书 ********");        // 解析book的属性        // 知道节点的属性名的时候获取属性值        System.out.println("id属性" + book.getAttributeValue("id"));        // 不知道属性的个数和属性名的时候        List<Attribute> attrList = book.getAttributes();        // 遍历book的属性集合        for (Attribute attribute : attrList) {            System.out.println("属性名:" + attribute.getName() + "-属性值:"                + attribute.getValue());            if ("id".equals(attribute.getName())) {            bookEntity.setId(attribute.getValue());            }        }        // 对book节点的子节点的节点名和节点值进行遍历        List<Element> bookChilds = book.getChildren();        for (Element child : bookChilds) {            System.out.println("节点名:" + child.getName() + "-节点值:"                + child.getValue());            if ("name".equals(child.getName())) {            bookEntity.setName(child.getValue());            } else if ("author".equals(child.getName())) {            bookEntity.setAuthor((child.getValue()));            } else if ("year".equals(child.getName())) {            bookEntity.setYear((child.getValue()));            } else if ("price".equals(child.getName())) {            bookEntity.setPrice(child.getValue());            } else if ("language".equals(child.getValue())) {            bookEntity.setLanguage(child.getValue());            }        }        System.out.println("******** 结束解析第"            + (bookList.indexOf(book) + 1) + "本书 ********\n");        booksList.add(bookEntity);        }        System.out.println("一共有" + booksList.size() + "本书!");        for (Book b : booksList) {        System.out.println(b);        }    } catch (FileNotFoundException e) {        e.printStackTrace();    } catch (JDOMException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    }    }}

运行结果:
结果

关于JDOM中jar包的引用

以上的jar包的导入方式实际上并没有真正地将jar包导入到项目中,仅仅是导入了jar包的引用。在进行项目的导入导出的时候,并不会连同jar包一起进行导入导出。当我们将项目迁移到另外一台电脑的时候,原先的jar包并不会存在;比较好的做法是在项目中新建一个目录,然后将jar文件添加到这个目录中再执行。
这里写图片描述
这里写图片描述
或者:
这里写图片描述

DOM4J方式解析XML

DOM4J1.6.1的下载地址:http://ncu.dl.sourceforge.net/project/dom4j/dom4j/1.6.1/dom4j-1.6.1.zip
解压得到如下文件:
DOM4J解压的结果
将jar包拷贝到项目中,再按照前面的方式Build Path。
实现如下:

import java.io.File;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;public class DOM4JTest {    public static void main(String[] args) {    // 1.创建一个SAXReader对象reader    SAXReader reader = new SAXReader();    try {        // 2.通过reader对象的read方法加载xml文件,获取Document对象        Document document = reader.read(new File("books.xml"));        Element bookStore = document.getRootElement();// 通过document对象获取根节点bookstore        // 获取根节点的子节点的相关信息        Iterator iterator = bookStore.elementIterator();// 通过Element对象的elementIterator方法获取迭代器        // 遍历迭代器,获取bookstore中的节点(book)        while (iterator.hasNext()) {        System.out.println("******** 开始遍历book ********");        Element book = (Element) iterator.next();        // 获取book的属性名和属性值        List<Attribute> bookAttrs = book.attributes();        for (Attribute attribute : bookAttrs) {            System.out.println("属性名:" + attribute.getName() + "-属性值:"                + attribute.getValue());        }        // 获取book的子节点        Iterator it = book.elementIterator();        while (it.hasNext()) {            Element bookChild = (Element) it.next();            System.out.println("节点名:" + bookChild.getName() + "-节点值:"                + bookChild.getStringValue());        }        System.out.println("******** 结束遍历book ********\n");        }    } catch (DocumentException e) {        e.printStackTrace();    }    }}

运行结果:
DOM4J方式解析XML的结果

4种解析XML方式的比较

这里写图片描述

0 0
原创粉丝点击