Java dom4j 读写xml文件 Demo

要生成/读取的文件

<?xml version="1.0" encoding="UTF-8"?>

<root attr="01">
	<text>hello</text>
	<row attr1="123" attr2="1234" attr3="0"/>
	<attr value="123">111</attr>
	<cycle>
		<info attr1="0" attr2="0" attr3="0"/>
		<info attr1="1" attr2="2" attr3="3"/>
		<info attr1="2" attr2="4" attr3="6"/>
		<info attr1="3" attr2="6" attr3="9"/>
		<info attr1="4" attr2="8" attr3="12"/>
		<info attr1="5" attr2="10" attr3="15"/>
		<info attr1="6" attr2="12" attr3="18"/>
		<info attr1="7" attr2="14" attr3="21"/>
		<info attr1="8" attr2="16" attr3="24"/>
		<info attr1="9" attr2="18" attr3="27"/>
	</cycle>
</root>

读写代码

package com.basic;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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;

/**
 * @author chichuduxing
 * @date 2016年12月15日 下午4:31:45
 */

public class XmlDemo {

	/**
	 * 日志对象
	 */
	private static final Log logger = LogFactory.getLog(XmlDemo.class);

	public static void main(String[] args) {
		String input = "./xml/xmldemo.xml";
		// String output = "./xml/writexmldemo.xml";

		WriteXml(input);

		ReadXml(input);
	}

	private static boolean ReadXml(String input) {
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(new File(input));
			if (null == document)
				throw new DocumentException("xml document is null. path:[" + input + "]");

			// 取 root 下的配置
			Element root = (Element) document.selectSingleNode("/root");
			if (null == root) {
				throw new DocumentException("xml document no root element. path:[" + input + "]");
			}

			getDisEmptyStringTextValue(root, "text");

			getEnEmptyStringTextValue(root, "text");

			Element row = root.element("row");
			if (null == row) {
				throw new DocumentException("xml document no row element. path:[" + input + "]");
			}

			logger.info("[/root/row-attr1] ==> [" + row.attributeValue("attr1") + "]");
			logger.info("[/root/row-attr2] ==> [" + row.attributeValue("attr2") + "]");
			logger.info("[/root/row-attr3] ==> [" + row.attributeValue("attr3") + "]");
			logger.info("[/root/row-attr4] ==> [" + row.attributeValue("attr4") + "]");

			getDisEmptyStringTextValue(root, "attr");
			getEnEmptyStringTextValue(root, "attr");

			Element attr = root.element("attr");
			if (null == attr) {
				throw new DocumentException("xml document no attr element. path:[" + input + "]");
			}

			logger.info("[/root/attr-value] ==> [" + attr.attributeValue("value") + "]");

			@SuppressWarnings("unchecked")
			List<Element> rows = root.selectNodes("cycle/info");
			for (Element elem : rows) {
				logger.info(elem.attributeValue("attr1") + "\t" + elem.attributeValue("attr2") + "\t"
						+ elem.attributeValue("attr3"));
			}

		} catch (DocumentException e) {
			e.printStackTrace();
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	private static void WriteXml(String output) {
		Document doc = DocumentHelper.createDocument();
		Element eltRoot = DocumentHelper.createElement("root");
		eltRoot.addAttribute("attr", "01");
		doc.setRootElement(eltRoot);

		Element eltext = eltRoot.addElement("text");
		eltext.setText("hello");

		Element elrow = eltRoot.addElement("row");
		elrow.addAttribute("attr1", "123");
		elrow.addAttribute("attr2", "1234");
		elrow.addAttribute("attr3", "0");

		Element elattr = eltRoot.addElement("attr");
		elattr.addAttribute("value", "123");
		elattr.setText("111");

		Element elcycle = eltRoot.addElement("cycle");
		Element ele = null;
		for (int i = 0; i < 10; i++) {
			ele = elcycle.addElement("info");
			ele.addAttribute("attr1", String.valueOf(i * 1));
			ele.addAttribute("attr2", String.valueOf(i * 2));
			ele.addAttribute("attr3", String.valueOf(i * 3));
		}

		XMLWriter xmlWriter = null;
		try {
			xmlWriter = initWriter(output);
			xmlWriter.write(doc);
			logger.info("Write [" + output + "] Done!");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("Write [" + output + "] Exception!" + e.getMessage());
		} finally {
			if (null != xmlWriter) {
				try {
					xmlWriter.close();
				} catch (IOException e) {
				}
			}
		}
	}

	private static XMLWriter initWriter(String filename) throws Exception {
		OutputFormat outFmt = OutputFormat.createPrettyPrint();
		outFmt.setEncoding("UTF-8");
		outFmt.setIndent("\t");
		XMLWriter xmlWriter = null;
		xmlWriter = new XMLWriter(new FileWriter(filename), outFmt);
		return xmlWriter;
	}

	private static String getDisEmptyStringTextValue(Element element, String config_item) throws Exception {
		String tmp = element.elementTextTrim(config_item);
		if (null == tmp || tmp.isEmpty()) {
			throw new Exception("[" + config_item + "] is empty,please check config.");
		} else {
			logger.info("[" + element.getPath() + "/" + config_item + "] ==> [" + tmp + "]");
		}
		return tmp;
	}

	private static String getEnEmptyStringTextValue(Element element, String config_item) throws Exception {
		String tmp = element.elementTextTrim(config_item);
		if (null == tmp || tmp.isEmpty()) {
			tmp = "";
			logger.warn("[" + element.getPath() + "/" + config_item + "] ==> [Empty]");
		} else {
			logger.info("[" + element.getPath() + "/" + config_item + "] ==> [" + tmp + "]");
		}
		return tmp;
	}
}

结果展示

展示读取结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值