Java 生成解析xml文件API一览

290 阅读5分钟

DOM

org.w3c.dom为文档对象模型 (DOM) 提供接口,该模型是 Java API for XML Processing 的组件 API。

生成xml文件示例

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();
    }
}

解析xml文件示例

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

JDOM的目的是成为 Java 特定文档模型,它简化与 XML 的交互并且比使用 DOM 实现更快。由于是第一个 Java 特定模型,JDOM 一直得到大力推广和促进。正在考虑通过“Java 规范请求 JSR-102”将它最终用作“Java 标准扩展”。

JDOM 文档声明其目的是“使用 20%(或更少)的精力解决 80%(或更多)Java/XML 问题”(根据学习曲线假定为 20%)。JDOM 对于大多数 Java/XML 应用程序来说当然是有用的,并且大多数开发者发现 API 比 DOM4J 容易理解得多。JDOM 还包括对程序行为的相当广泛检查以防止用户做任何在 XML 中无意义的事。然而,它仍需要您充分理解 XML 以便做一些超出基本的工作(或者甚至理解某些情况下的错误)。这也许是比学习 DOM4J 或 JDOM 接口都更有意义的工作。 JDOM 自身不包含解析器。它通常使用 SAX2 解析器来解析和验证输入 XML 文档(尽管它还可以将以前构造的 DOM 表示作为输入)。它包含一些转换器以将 JDOM 表示输出成 SAX2 事件流、DOM 模型或 XML 文本文档。JDOM 是在 Apache 许可证变体下发布的开放源码。

JDOM 在性能测试时表现不佳,在测试 10M 文档时内存溢出。在小文档情况下还值得考虑使用 JDOM。

生成xml文件示例

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(newFile("BookstorebyJDOM.xml")));
        }
}

解析xml文件示例

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

DOM4J是 JDOM 的一种智能分支。它合并了许多超出基本 XML 文档表示的功能,包括集成的 XPath 支持、XML Schema 支持以及用于大文档或流化文档的基于事件的处理。它还提供了构建文档表示的选项,它通过 DOM4J API 和标准 DOM 接口具有并行访问功能。DOM4J 大量使用了 API 中的 Collections 类,但是在许多情况下,它还提供一些替代方法以允许更好的性能或更直接的编码方法。直接好处是,虽然 DOM4J 付出了更复杂的 API 的代价,但是它提供了比 JDOM 大得多的灵活性。在添加灵活性、XPath 集成和对大文档处理的目标时,DOM4J 的目标与 JDOM 是一样的:针对 Java 开发者的易用性和直观操作。它还致力于成为比 JDOM 更完整的解决方案,实现在本质上处理所有 Java/XML 问题的目标。在完成该目标时,它比 JDOM 更少强调防止不正确的应用程序行为。

DOM4J 是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件。如今你可以看到越来越多的 Java 软件都在使用 DOM4J 来读写 XML,特别值得一提的是连 Sun 的 JAXM 也在用 DOM4J。

生成xml文件示例

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();
                // 设置XML文档格式
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();  
        // 设置XML编码方式,即是用指定的编码方式保存XML文档到字符串(String),这里也可以指定为GBK或是ISO8859-1  
        outputFormat.setEncoding("UTF-8");
        //outputFormat.setSuppressDeclaration(true); //是否生产xml头
        outputFormat.setIndent(true); //设置是否缩进
        outputFormat.setIndent("    "); //以四个空格方式实现缩进
        outputFormat.setNewlines(true); //设置是否换行
        outputFormat.setIndentSize(4);
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(new File(
                "BookstorebyDOM4J.xml")), outputFormat);
        xmlWriter.write(document);
        xmlWriter.close();
    }
}

解析xml文件示例

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());
        }
    }
}
public static void main(String[] args) throws DocumentException {
     String xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<products>"
                + "<subject><subjectName>1</subjectName><subjectUrl>333</subjectUrl></subject>"
                + "</products>";
    //获取sax解析器对象
    SAXReader reader = new SAXReader();
    //转换字符串为java.io.Reader对象
    Reader stringReader=new StringReader(xml);
    //读取Reader对象,获取Document对象
    Document document=reader.read(stringReader);
    //获取根元素
    Element root = document.getRootElement();
    //获取根元素的名称
    String  rootName=root.getName();
    System.out.println("根节点名称: "+rootName);
    //获取子节点subject
    Element child1=root.element("subject");
    //获取子节点subjectName
    Element child2=child1.element("subjectName");
    String child2Name=child2.getName();
    String child2Text=child2.getText();
    System.out.println("子节点subjectName名称: "+child2Name);
    System.out.println("子节点subjectName内容: "+child2Text);
}