继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

浅谈(易学)DOM、JDOM、DOM4J三种解析和生成xml

Allen_______
关注TA
已关注
手记 3
粉丝 7
获赞 264

恩,在学完了DOM、JDOM、DOM4J、SAX几种解析和生成xml文件之后做的小总结,认真看完估计对读者还是很有帮助的,当然要有这部分一定的基础了,sax是基于事件驱动的,它的解析和生成xml与其他三种还是有较大差别的,但掌握了原理后其也是相当简单的,不过这部分,我就先略过的。跟大家分享其他三种方法解析和生成xml.
在解析过程中,我都进行了数据的类的封装,将某类数据存入某类的某个对象(通过类的不同字段接收不同数据),然后将多个对象存入集合之中。方便随时处理。
一:首先是解析Bookstore。xml文件
图片描述
①:下面是DOM解析代码
package DOMparse;

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

public class DOMtest {
static int bookindex;
static Book onebook = null;
static List<Book> booklist = new ArrayList<Book>();

public static void main(String[] args) throws ParserConfigurationException,
        SAXException, IOException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory
            .newDocumentBuilder();
    Document document = documentBuilder.parse("Bookstore.xml");
    Node bookstore = document.getChildNodes().item(0);

    if (bookstore.getNodeType() == Node.ELEMENT_NODE) {

        NodeList books = bookstore.getChildNodes();
        for (int j = 0; j < books.getLength(); j++) {
            onebook = new Book();
            Node book = books.item(j);

            if (book.getNodeType() == Node.ELEMENT_NODE) {

                NamedNodeMap bookattributes = book.getAttributes();
                for (int i = 0; i < bookattributes.getLength(); i++) {
                    Node attribute = bookattributes.item(i);
                    if (attribute.getNodeType() == Node.ATTRIBUTE_NODE) {

                        if (attribute.getNodeName() == "id") {
                            onebook.setId(attribute.getNodeValue());
                        }
                        if (attribute.getNodeName() == "other") {
                            onebook.setOther(attribute.getNodeValue());
                        }
                    }
                }
                NodeList bookchilds = book.getChildNodes();
                for (int k = 0; k < bookchilds.getLength(); k++) {
                    Node bookchild = bookchilds.item(k);
                    if (bookchild.getNodeName() == "Name") {
                        onebook.setName(bookchild.getTextContent());
                    }
                    if (bookchild.getNodeName() == "Price") {
                        onebook.setPrice(bookchild.getTextContent());
                    }
                    if (bookchild.getNodeName() == "Type") {
                        onebook.setType(bookchild.getTextContent());
                    }
                    if (bookchild.getNodeName() == "Author") {
                        onebook.setAuthor(bookchild.getTextContent());
                    }
                }
                booklist.add(onebook);
            }
        }
    }
    for (Book book : booklist) {
        System.out.println("=====存放入list然后输出第" + (++bookindex)
                + "本书信息=====");
        System.out.println("该书编号:" + book.getId());
        System.out.println("该书名字:" + book.getName());
        System.out.println("该书作者:" + book.getAuthor());
        System.out.println("该书价格:" + book.getPrice());
        System.out.println("该书类型:" + book.getType());
        System.out.println("该书信息:" + book.getOther());
    }
}

}
②下面是JDOM解析:
package JDOMparse;

import java.io.File;
import java.io.IOException;
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 {
static int bookindex;
static List<Book> booklist = new ArrayList<Book>();
static Book onebook = null;

public static void main(String[] args) throws JDOMException, IOException {
    SAXBuilder saxBuilder = new SAXBuilder();
    Document document = saxBuilder.build(new File("Bookstore.xml"));
    Element bookstore = document.getRootElement();
    List<Element> books = bookstore.getChildren();
    for (int i = 0; i < books.size(); i++) {
        onebook = new Book();

        Element book = books.get(i);
        List<Attribute> bookAttributes = book.getAttributes();
        for (int j = 0; j < bookAttributes.size(); j++) {
            Attribute bookaAttribute = bookAttributes.get(j);
            if (bookaAttribute.getName() == "id") {
                onebook.setId(bookaAttribute.getValue());
            }
            if (bookaAttribute.getName() == "other") {
                onebook.setOther(bookaAttribute.getValue());
            }
        }
        List<Element> bookchilds = book.getChildren();
        for (int j = 0; j < bookchilds.size(); j++) {
            Element bookchild = bookchilds.get(j);
            if (bookchild.getName() == "Author") {
                onebook.setAuthor(bookchild.getText());
            }
            if (bookchild.getName() == "Name") {
                onebook.setName(bookchild.getText());
            }
            if (bookchild.getName() == "Price") {
                onebook.setPrice(bookchild.getText());
            }
            if (bookchild.getName() == "Type") {
                onebook.setType(bookchild.getText());
            }
        }
        booklist.add(onebook);

    }
    for (Book book : booklist) {
        System.out.println("=====存放入list然后输出第" + (++bookindex)
                + "本书信息=====");
        System.out.println("该书编号:" + book.getId());
        System.out.println("该书名字:" + book.getName());
        System.out.println("该书作者:" + book.getAuthor());
        System.out.println("该书价格:" + book.getPrice());
        System.out.println("该书类型:" + book.getType());
        System.out.println("该书信息:" + book.getOther());
    }
}

}

③下面是DOM4J解析:
package DOM4Jparse;

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;

public class DOM4Jtest {
static int bookindex;
static Book oneBook;
static List<Book> booklist = new ArrayList<Book>();

@SuppressWarnings("unchecked")
public static void main(String[] args) throws DocumentException {
    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(new File("Bookstore.xml"));
    Element bookstore = document.getRootElement();
    Iterator books = bookstore.elementIterator();

    while (books.hasNext()) {
        oneBook = new Book();
        Element book = (Element) books.next();

        List<Attribute> bookattributes = book.attributes();
        for (int i = 0; i < bookattributes.size(); i++) {
            Attribute bookattribute = bookattributes.get(i);
            if (bookattribute.getName() == "id") {
                oneBook.setId(bookattribute.getValue());
            }
            if (bookattribute.getName() == "other") {
                oneBook.setOther(bookattribute.getValue());
            }
        }
        Iterator bookchilds = book.elementIterator();
        while (bookchilds.hasNext()) {
            Element bookchild = (Element) bookchilds.next();
            if (bookchild.getName() == "Name") {
                oneBook.setName(bookchild.getText());
            }
            if (bookchild.getName() == "Author") {
                oneBook.setAuthor(bookchild.getText());
            }
            if (bookchild.getName() == "Price") {
                oneBook.setPrice(bookchild.getText());
            }
            if (bookchild.getName() == "Type") {
                oneBook.setType(bookchild.getText());
            }
        }
        booklist.add(oneBook);

    }
    for (Book book : booklist) {
        System.out.println("=====存放入list然后输出第" + (++bookindex)
                + "本书信息=====");
        System.out.println("该书编号:" + book.getId());
        System.out.println("该书名字:" + book.getName());
        System.out.println("该书作者:" + book.getAuthor());
        System.out.println("该书价格:" + book.getPrice());
        System.out.println("该书类型:" + book.getType());
        System.out.println("该书信息:" + book.getOther());
    }

}

}

上面几种解析很相似,注意DOM是结构树跨语言的,别的语言也识别该DOM树,JDOM是对底层API的封装,DOM4J是JDOM的一个优秀分支也是相当不错的。重点是文档准备工作做好,下面根据方法也能摸索的出来吧!
二、下面讲DOM、JDOM、DOM4J三种生成xml的方式
①、DOM生成xml:(我为了大家方便查看,写了一部分大家可补充完善)
package DOM4Jproduce;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class DOM4Jsettest {
public static void main(String[] args) throws IOException {
Document document = DocumentHelper.createDocument();
Element bookstore = document.addElement("bookstore");
Element book1 = bookstore.addElement("book");
book1.addAttribute("id", "book1");
book1.addAttribute("other", "这是第二本书");
Element Name = book1.addElement("Name");
Element Author = book1.addElement("Author");
Element Type = book1.addElement("Type");
Element Price = book1.addElement("Price");
Author.addText("天哥哥");
Name.addText("Get Me Fly");
Price.addText("999RMB");
Type.addText("励志");
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
outputFormat.setEncoding("UTF-8");
outputFormat.setIndentSize(4);
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(new File(
"BookstorebyDOM4J.xml")), outputFormat);
xmlWriter.write(document);
xmlWriter.close();
}
}
①①对应的BookstoreDOM4J.xml为:
图片描述

②JDOM方式生成xml方式:(同二①)
package JDOMproduce;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class JDOMsettest {
public static void main(String[] args) throws FileNotFoundException,
IOException {
Element bookstore = new Element("Bookstore");
Document document = new Document(bookstore);
Element book1 = new Element("book");
bookstore.addContent(book1);
Element Name = new Element("Name");
book1.addContent(Name);
Element Author = new Element("Author");
book1.addContent(Author);
Element Type = new Element("Type");
book1.addContent(Type);
Element Price = new Element("Price");
book1.addContent(Price);
book1.setAttribute("id", "book1");
book1.setAttribute("other", "这是第一本书");
Name.setText("Get Me fLy");
Author.setText("天哥哥");
Price.setText("999RMB");
Type.setText("励志");
Format format = Format.getPrettyFormat();
format.setEncoding("UTF-8");
format.setIndent(" ");
XMLOutputter xmlOutputter = new XMLOutputter(format);
xmlOutputter.output(document, new FileOutputStream(new File(
"BookstorebyJDOM.xml")));

}

}
②②对应BookstorebyJDOM.xml文件为:
图片描述
③DOM4J生成xml方式为:(同二①)
package DOM4Jproduce;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class DOM4Jsettest {
public static void main(String[] args) throws IOException {
Document document = DocumentHelper.createDocument();
Element bookstore = document.addElement("bookstore");
Element book1 = bookstore.addElement("book");
book1.addAttribute("id", "book1");
book1.addAttribute("other", "这是第二本书");
Element Name = book1.addElement("Name");
Element Author = book1.addElement("Author");
Element Type = book1.addElement("Type");
Element Price = book1.addElement("Price");
Author.addText("天哥哥");
Name.addText("Get Me Fly");
Price.addText("999RMB");
Type.addText("励志");
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
outputFormat.setEncoding("UTF-8");
outputFormat.setIndentSize(4);
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(new File(
"BookstorebyDOM4J.xml")), outputFormat);
xmlWriter.write(document);
xmlWriter.close();
}
}
③③BookstorebyDOM4J.xml文件为:
图片描述

打开App,阅读手记
11人推荐
发表评论
随时随地看视频慕课网APP

热门评论

感谢分享。。。。。。

不错不错,3种方法都很像,会一种,学其它两种,都比较简单了。期待小编的sax解析。

查看全部评论