java DOM4J 讀取XML執行個體代碼_java

來源:互聯網
上載者:User

下面展示一篇我自己寫的一個XML讀取測試

複製代碼 代碼如下:

import java.util.Iterator;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

public class XmlRead {

    static StringBuilder sBuilder = new StringBuilder();

    public static void main(String[] args) throws IOException {

        BufferedReader bReader = new BufferedReader(new InputStreamReader(
                System.in));
        String path = null;
        System.out.println("請輸入XML檔案的絕對路徑以及檔案名稱:\n");
        path = bReader.readLine();

        sBuilder.append("開始輸出XML檔案內容\n");

        Document document = null;
        try {
            document = read(path);
            sBuilder.append(path + "\n");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        Element root = getRootElement(document);
        if (root == null) {
            System.out.print("沒有擷取到root節點");
            return;
        }
        // 擷取XML文檔的編碼格式
        String encString = document.getXMLEncoding();
        sBuilder.append("<?xml version=\"1.0\" encoding=\"" + encString
                + "\">\n");
        sBuilder.append(elementText(root, attText(root), 0));

        System.out.println(getIterator(root, 0) + "</" + root.getName() + ">");

    }

    /**
     * 遞迴節點
     *
     * @description
     * @param element
     * @param lvl
     *            層級
     * @return
     */
    private static String getIterator(Element element, int lvl) {

        lvl += 1;

        for (Iterator i = element.elementIterator(); i.hasNext();) {
            Element e = (Element) i.next();
            sBuilder.append(elementText(e, attText(e), lvl));
            getIterator(e, lvl);

            int count = e.nodeCount();

            if (count > 0) {
                for (int j = 0; j < lvl; j++) {
                    sBuilder.append("    ");
                }
            }
            sBuilder.append("</" + e.getName() + ">\n");
        }

        return sBuilder.toString();
    }

    /**
     * 擷取當前節點的屬性的值的字串
     *
     * @description
     * @param element
     *            當前節點
     * @return
     */
    private static String attText(Element element) {

        String str = " ";
        for (int i = 0; i < element.attributeCount(); i++) {
            Attribute attribute = element.attribute(i);

            str += attribute.getName() + "=\"" + attribute.getValue() + "\" ";
        }
        return str;
    }

    /**
     * 擷取當前Element的文本值
     *
     * @description
     * @param element
     *            當前Element節點
     * @param text
     *            屬性值
     * @param lvl
     *            層級
     * @return
     */
    private static String elementText(Element element, String text, int lvl) {
        String str = "";
        for (int i = 0; i < lvl; i++) {
            str += "    ";
        }
        str += "<" + element.getName();
        if (text != null && text != "") {
            str += text;
        }
     //由於dom4j裡面沒有 hasChild這個屬性或者方法,所以要用nodeCount()這個方法來判斷時候還有子節點
        int count = element.nodeCount();
        if (count == 0) {
            return str += ">";
        }
        return str += ">\n";
    }

    /**
     *
     * @description 讀取XML檔案
     * @param file
     *            XML檔案路徑,包含檔案名稱
     * @return Document 文檔
     * @throws MalformedURLException
     * @throws DocumentException
     */
    public static Document read(String file) throws MalformedURLException,
            DocumentException {

        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(file));
        return document;
    }

    /**
     * 擷取Document文檔的root節點
     *
     * @param document
     * @return
     */
    public static Element getRootElement(Document document) {
        return document.getRootElement();
    }

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.