全屏浏览
缩小浏览
回到页首

java三方---->dom4j解析xml数据

  Dom4j是一个易用的、开源的库,用于XML,XPath和XSLT。它应用于Java平台,采用了Java集合框架并完全支持DOM,SAX和JAXP。今天我们就开始Dom4j的学习。

Dom4j的使用

dom4j的使用项目结构如下:

Dom4j的下载地址:https://sourceforge.net/projects/dom4j/?source=typ_redirect

一、请求数据,并且保存到本地文件中

private static String fileName = "file/huhxDom.xml";
private static String requestUrl = "http://wcf.open.cnblogs.com/blog/u/huhx/posts/1/3";

// 将url的内容读取到本地文件夹中
public static void writeFileFromUrl(String strUrl) {
    HttpURLConnection connection = null;
    OutputStream outputStream = null;
    InputStream inputStream = null;
    try {
        URL url = new URL(strUrl);
        connection = (HttpURLConnection) url.openConnection();
        outputStream = new FileOutputStream(new File(fileName));
        connection.setConnectTimeout(8000);
        connection.setReadTimeout(8000);
        connection.setRequestMethod("GET");

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = connection.getInputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            outputStream.close();
            inputStream.close();
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

二、从本地文件中读取数据并解析:

// 解析文件,将内容取出来
public static void readFromFile() {
    SAXReader reader = new SAXReader();
    try {
        Document document = reader.read(new File(fileName));
        Element rootElement = document.getRootElement();
        // 博客logo的路径
        System.out.println("logo: " + rootElement.elementText("logo"));

        // 网页的标题
        System.out.println("title: " + rootElement.elementText("title"));

        // 发布博客数量
        System.out.println("postcount: " + rootElement.elementText("postcount"));

        // 博客作者信息
        Element authorElement = rootElement.element("author");
        System.out.println("authorName: " + authorElement.elementText("name"));
        System.out.println("authorUri: " + authorElement.elementText("uri"));
        System.out.println("-------------------------------------------------------");

        // 博客的列表,所有的entry列表
        @SuppressWarnings("unchecked")
        List<Element> entries = rootElement.elements("entry");
        for (Element entry : entries) {
            System.out.println("entryId: " + entry.elementText("id"));
            System.out.println("entryTitle: " + entry.elementText("title").replaceAll("&gt;", ">"));
            System.out.println("entrySummary: " + entry.elementTextTrim("summary"));
            System.out.println("entryLink: " + entry.element("link").attributeValue("href"));
            System.out.println("***************************************************");
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

 

三、得到下载的xml文件huhxDom.xml内容如下:

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title type="text">博客园_huhx</title>
    <id>uuid:a0d85c23-4321-4ed6-938b-c6924edf816d;id=18947</id>
    <updated>2016-06-07T11:40:07+08:00</updated>
    <logo>http://pic.cnblogs.com/face/849920/20160316222225.png</logo>
    <author>
        <name>huhx</name>
        <uri>http://www.cnblogs.com/huhx/</uri>
    </author>
    <postcount>68</postcount>
    <entry>
        <id>5564873</id>
        <title type="text">js插件----&amp;gt;日期控件My97DataPicker的使用</title>
        <summary type="text">My97DatePicker是一个更全面,更人性化,并且速度一流的日期选择控件。具有强大的日期范围限制功能;自定义事件和丰富的API库;多语言支持和自定义皮肤支持;跨无限级框架显示和自动选择显示位置。今天我们就开始My97DatePicker的基础使用。
            日期控件My97DataPicker 一、将
        </summary>
        <published>2016-06-07T11:40:00+08:00</published>
        <updated>2016-06-07T11:16:35Z</updated>
        <author>
            <name>huhx</name>
            <uri>http://www.cnblogs.com/huhx/</uri>
        </author>
        <link rel="alternate"
            href="http://www.cnblogs.com/huhx/p/jsThirdMy97DataPicker.html" />
        <diggs>0</diggs>
        <views>7</views>
        <comments>0</comments>
    </entry>
    <entry>
        <id>5563444</id>
        <title type="text">js插件----&amp;gt;jquery通知插件toastr的使用</title>
        <summary type="text">toastr是一款非常棒的基于jquery库的非阻塞通知提示插件,toastr可设定四种通知模式:成功,出错,警告,提示,而提示窗口的位置,动画效果都可以通过能数来设置。toastr需要jquery的支持。今天我们就开始toastr的学习。
            jquery通知插件toastr的使用 一、引入jquer
        </summary>
        <published>2016-06-06T18:50:00+08:00</published>
        <updated>2016-06-07T11:16:35Z</updated>
        <author>
            <name>huhx</name>
            <uri>http://www.cnblogs.com/huhx/</uri>
        </author>
        <link rel="alternate" href="http://www.cnblogs.com/huhx/p/jsThirdToastr.html" />
        <diggs>0</diggs>
        <views>17</views>
        <comments>0</comments>
    </entry>
    <entry>
        <id>5557028</id>
        <title type="text">java三方----&amp;gt;html解析jsoup的使用</title>
        <summary type="text">jsoup 是一款 Java 的HTML
            解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于JQuery的操作方法来取出和操作数据。今天我们就开始jsoup的学习。
            jsoup解析html jsoup的主要功能如下: 从一个URL,文件或
        </summary>
        <published>2016-06-03T17:30:00+08:00</published>
        <updated>2016-06-07T11:16:35Z</updated>
        <author>
            <name>huhx</name>
            <uri>http://www.cnblogs.com/huhx/</uri>
        </author>
        <link rel="alternate" href="http://www.cnblogs.com/huhx/p/javaThirdJsoup.html" />
        <diggs>0</diggs>
        <views>103</views>
        <comments>0</comments>
    </entry>
</feed>

 

四、解析该文件,得到博客的相关信息:

logo: http://pic.cnblogs.com/face/849920/20160316222225.png
title: 博客园_huhx
postcount: 68
authorName: huhx
authorUri: http://www.cnblogs.com/huhx/
-------------------------------------------------------
entryId: 5564873
entryTitle: js插件---->日期控件My97DataPicker的使用
entrySummary: My97DatePicker是一个更全面,更人性化,并且速度一流的日期选择控件。具有强大的日期范围限制功能;自定义事件和丰富的API库;多语言支持和自定义皮肤支持;跨无限级框架显示和自动选择显示位置。今天我们就开始My97DatePicker的基础使用。 日期控件My97DataPicker 一、将
entryLink: http://www.cnblogs.com/huhx/p/jsThirdMy97DataPicker.html
***************************************************
entryId: 5563444
entryTitle: js插件---->jquery通知插件toastr的使用
entrySummary: toastr是一款非常棒的基于jquery库的非阻塞通知提示插件,toastr可设定四种通知模式:成功,出错,警告,提示,而提示窗口的位置,动画效果都可以通过能数来设置。toastr需要jquery的支持。今天我们就开始toastr的学习。 jquery通知插件toastr的使用 一、引入jquer
entryLink: http://www.cnblogs.com/huhx/p/jsThirdToastr.html
***************************************************
entryId: 5557028
entryTitle: java三方---->html解析jsoup的使用
entrySummary: jsoup 是一款 Java 的HTML 解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于JQuery的操作方法来取出和操作数据。今天我们就开始jsoup的学习。 jsoup解析html jsoup的主要功能如下: 从一个URL,文件或
entryLink: http://www.cnblogs.com/huhx/p/javaThirdJsoup.html
***************************************************

 Dom4jTest.java文件的内容:

package com.huhx.dom4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Dom4jTest {
    private static String fileName = "file/huhxDom.xml";
    private static String requestUrl = "http://wcf.open.cnblogs.com/blog/u/huhx/posts/1/3";

    // 将url的内容读取到本地文件夹中
    public static void writeFileFromUrl(String strUrl) {
        HttpURLConnection connection = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(strUrl);
            connection = (HttpURLConnection) url.openConnection();
            outputStream = new FileOutputStream(new File(fileName));
            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);
            connection.setRequestMethod("GET");

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, length);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
                inputStream.close();
                connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 解析文件,将内容取出来
    public static void readFromFile() {
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new File(fileName));
            Element rootElement = document.getRootElement();
            // 博客logo的路径
            System.out.println("logo: " + rootElement.elementText("logo"));

            // 网页的标题
            System.out.println("title: " + rootElement.elementText("title"));

            // 发布博客数量
            System.out.println("postcount: " + rootElement.elementText("postcount"));

            // 博客作者信息
            Element authorElement = rootElement.element("author");
            System.out.println("authorName: " + authorElement.elementText("name"));
            System.out.println("authorUri: " + authorElement.elementText("uri"));
            System.out.println("-------------------------------------------------------");

            // 博客的列表
            @SuppressWarnings("unchecked")
            List<Element> entries = rootElement.elements("entry");
            for (Element entry : entries) {
                System.out.println("entryId: " + entry.elementText("id"));
                System.out.println("entryTitle: " + entry.elementText("title").replaceAll("&gt;", ">"));
                System.out.println("entrySummary: " + entry.elementTextTrim("summary"));
                System.out.println("entryLink: " + entry.element("link").attributeValue("href"));
                System.out.println("***************************************************");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        writeFileFromUrl(requestUrl);
        readFromFile();
    }
}
View Code

 

对Dom4j的一些源码

以下贴出一些Dom4j的重要方法的源码。

一、elementIterator方法

public Iterator elementIterator(String name) {
    List list = elements(name);
    return list.iterator();
}

二、elementText方法

public String elementText(String name) {
    Element element = element(name);
    return (element != null) ? element.getText() : null;
}

三、attributeValue方法

public String attributeValue(String name) {
    Attribute attrib = attribute(name);

    if (attrib == null) {
        return null;
    } else {
        return attrib.getValue();
    }
}

四、element方法

public Element element(String name) {
    List list = contentList();
    int size = list.size();

    for (int i = 0; i < size; i++) {
        Object object = list.get(i);

        if (object instanceof Element) {
            Element element = (Element) object;

            if (name.equals(element.getName())) {
                return element;
            }
        }
    }
    return null;
}

 五、elementTextTrim方法

public String elementTextTrim(String name) {
    Element element = element(name);
    return (element != null) ? element.getTextTrim() : null;
}

element.getTextTrim()方法的说明:

return: the trimmed text value where whitespace is trimmed and normalised into single spaces. This method does not return null.

 

友情链接

 

posted @ 2016-06-08 09:08  huhx  阅读(819)  评论(0编辑  收藏  举报