dom4j 工具類

package org.wanda.work.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 操作XML文件的工具類
 */
public class XMLUtil {
    /**
     * 得到XML文檔
     *
     * @param xmlFile
     *            文件名(路徑)
     * @return XML文檔對象
     * @throws DocumentException
     */
    public static Document getDocument(String xmlFile) {
        SAXReader reader = new SAXReader();
        reader.setEncoding("UTF-8");
        File file = new File(xmlFile);
        try {
            if (!file.exists()) {
                return null;
            } else {
                return reader.read(file);
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e + "->指定文件【" + xmlFile + "】讀取錯誤");
        }
    }

    /**
     * 得到XML文檔(編碼格式-gb2312)
     *
     * @param xmlFile
     *            文件名(路徑)
     * @return XML文檔對象
     * @throws DocumentException
     */
    public static Document getDocument_gb2312(String xmlFile) {
        SAXReader reader = new SAXReader();
        reader.setEncoding("gb2312");
        File file = new File(xmlFile);
        try {
            if (!file.exists()) {
                return null;
            } else {
                return reader.read(file);
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e + "->指定文件【" + xmlFile + "】讀取錯誤");
        }
    }

    public static String getText(Element element) {
        try {
            return element.getTextTrim();
        } catch (Exception e) {
            throw new RuntimeException(e + "->指定【" + element.getName() + "】節點讀取錯誤");
        }

    }

    /**
     * 增加xml文件節點
     *
     * @param document
     *            xml文檔
     * @param elementName
     *            要增加的元素名稱
     *            要增加的元素屬性
     *            要增加的元素屬性值
     */
    public static Document addElementByName(Document document, String elementName, Map<String, String> attrs, String cdata) {
        try {
            Element root = document.getRootElement();
            Element subElement1 = root.addElement(elementName+"s");
            Element subElement = subElement1.addElement(elementName);

            for (Map.Entry<String, String> attr : attrs.entrySet()) {
                subElement.addAttribute(attr.getKey(), attr.getValue());
            }
           // subElement.addCDATA("");
        } catch (Exception e) {
            throw new RuntimeException(e + "->指定的【" + elementName + "】節點增加出現錯誤");
        }
        return document;
    }

    /**
     * 刪除xml文件節點
     */
    @SuppressWarnings("unchecked")
    public static Document deleteElementByName(Document document, String elementName) {
        Element root = document.getRootElement();
        Iterator<Object> iterator = root.elementIterator("file");
        while (iterator.hasNext()) {
            Element element = (Element) iterator.next();
            // 根據屬性名獲取屬性值
            Attribute attribute = element.attribute("name");
            if (attribute.getValue().equals(elementName)) {
                root.remove(element);
                document.setRootElement(root);
                break;
            }
        }
        return document;
    }

    /**
     * 輸出xml文件
     *
     * @param document
     * @param filePath
     * @throws IOException
     */
    public static void writeXml(Document document, String filePath) throws IOException {
        File xmlFile = new File(filePath);
        XMLWriter writer = null;
        try {
            if (xmlFile.exists())
                xmlFile.delete();
            writer = new XMLWriter(new FileOutputStream(xmlFile), OutputFormat.createPrettyPrint());
            writer.write(document);
            writer.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    /**
     * 創建Document及根節點
     *
     * @param rootName
     * @param attributeName
     * @param attributeVaule
     * @return
     */
    public static Document createDocument(String rootName, String attributeName, String attributeVaule) {
        Document document = null;
        try {
            document = DocumentHelper.createDocument();
            Element root = document.addElement(rootName);
            root.addAttribute(attributeName, attributeVaule);
        } catch (Exception e) {
            throw new RuntimeException(e + "->創建的【" + rootName + "】根節點出現錯誤");
        }
        return document;
    }

    /**
     * 刪除xml文件節點
     */
    @SuppressWarnings("unchecked")
    public static Document deleteElementAddressByName(Document document, String elementName) {
        Element root = document.getRootElement();
        Iterator<Object> iterator = root.elementIterator("address");
        while (iterator.hasNext()) {
            Element element = (Element) iterator.next();
            // 根據屬性名獲取屬性值
            Attribute attribute = element.attribute("name");
            if (attribute.getValue().equals(elementName)) {
                root.remove(element);
                document.setRootElement(root);
                break;
            }
        }
        return document;
    }

    /**
     *    刪除屬性等於某個值的元素
     *    @param document  XML文檔
     *    @param xpath xpath路徑表達式
     *    @param attrName 屬性名
     *    @param attrValue 屬性值
     *    @return
     */
    @SuppressWarnings("unchecked")
    public static Document deleteElementByAttribute(Document document, String xpath, String attrName, String attrValue) {
        Iterator<Object> iterator = document.selectNodes(xpath).iterator();
        while (iterator.hasNext()) {
            Element element = (Element) iterator.next();
            Element parentElement = element.getParent();
            // 根據屬性名獲取屬性值
            Attribute attribute = element.attribute(attrName);
            if (attribute.getValue().equals(attrValue)) {
                parentElement.remove(element);
            }
        }
        return document;
    }
}


















在指定位置插入節點


Element root = document.getRootElement();
Element element = (Element) root.selectNodes("/solr/cores").get(0);
Element itemElement = DocumentHelper.createElement("core");
for (Map.Entry<String, String> attr : attrs.entrySet()) {
    itemElement.addAttribute(attr.getKey(), attr.getValue());
}
element.add(itemElement);



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章