自定义容易XML的读与存,便捷工具类

自定义简单XML的读与存,便捷工具类
主要依赖jar包dom4j.jar ,main方法中有使用方法
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * XML数据元素操作基类
 * 
 * @author Administrator
 * 
 */
public class CacheNodeBaseVO implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3821539085598864455L;

	// 参数传递
	protected HashMap<String,Object> parameters = null;

	public CacheNodeBaseVO() {
		this.parameters = new HashMap<String, Object>();
	}
	
	/**
	 * 加参数
	 */
	public void addParam(String name, Object value) {
		this.parameters.put(name, value);
	}

	/**
	 * 增加加参数
	 * 
	 * @param map
	 */
	public void addParam(Map map) {
		if(map==null || map.size()<=0){
			return;
		}
		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			String key = String.valueOf(it.next());			
			Object value = map.get(key);
			addParam(key, value);
		}
	}

	/**
	 * 删除参数
	 * 
	 * @param key
	 */
	public void removeParam(String key) {
		this.parameters.remove(key);
	}

	public void removeAllParams() {
		this.parameters.clear();
	}

	public String getParam(String key) {
		return (String) this.parameters.get(key);
	}
	
	public Object getParamObj(String key) {
		return this.parameters.get(key);
	}

	public HashMap<String,Object> getParameters() {
		return parameters;
	}

	public void setParameters(HashMap parameters) {
		this.parameters = parameters;
	}

	public String toString() {
		StringBuffer sb = new StringBuffer();
		Iterator it = this.parameters.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			sb.append(key + ":" + this.parameters.get(key) + ";");
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		CacheNodeBaseVO vo = new CacheNodeBaseVO();
		vo.addParam("fdiId","22");
		vo.addParam("fdiId2","22");
		vo.addParam("fdiId3","22");
		vo.addParam("fdiId4","22");
		vo.addParam("fdiId5","22");
		System.out.println(vo.toString());
		
	}
}

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

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

import com.etone.util.XMLUtils;

/**
 * XML数据元素操作基类
 * 
 * @author Administrator
 * 
 */
public class CacheNodeVO extends CacheNodeBaseVO implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3821539085598864455L;

	private Document node = null;

	private Element root = null;

	private List subNodes = null;

	private Element parent = null;

	// fdc属性为null时的默认值
	private String fdcDefaultValue = "";

	// fdi属性为null时的默认值
	private String fdiDefaultValue = "0";

	// fdd属性为null时的默认值
	private String fddDefaultValue = "00:00";

	/**
	 * 构造方法,root名称为"root"
	 * 
	 */
	public CacheNodeVO() {
		this("Node");
	}

	/**
	 * 构造方法
	 * 
	 * @param rootName
	 *            根据元素名
	 */
	public CacheNodeVO(String rootName) {
		this.node = DocumentHelper.createDocument();
		this.root = this.node.addElement(rootName);
		this.subNodes = new ArrayList();
		this.parent = this.node.getParent();
	}

	/**
	 * 修改本结果的name
	 * 
	 * @param name
	 */
	public void setNodeName(String name) {
		this.root.setName(name);
	}

	/**
	 * 把属性加到本节点元素中
	 */
	public Element addAttribute(String name, String value) {
		if (name == null) {
			return null;
		}
		if (value == null) {
			if (name.startsWith("fdi")) {
				value = fdiDefaultValue;
			} else if (name.startsWith("fdc")) {
				value = fdcDefaultValue;
			} else if (name.startsWith("fdd")) {
				value = fddDefaultValue;
			} else
				value = "-";
		}
		return this.root.addAttribute(name, value);
	}

	/**
	 * 取属性值
	 * 
	 * @param name
	 * @return String
	 * @date 2008-3-20
	 * @package com.etone.dao.vo
	 */
	public String getAttribute(String name) {
		return this.root.attributeValue(name);
	}

	/**
	 * 把属性加到本节点元素中
	 */
	public Element addAttribute(Attribute attribute) {
		this.root.add(attribute);
		return root;
	}

	/**
	 * 从本节点元素中移除某指定属性
	 */
	public boolean removeAttribute(String key) {
		return this.root.remove(this.root.attribute(key));
	}

	/**
	 * 从本节点元素中移除某指定属性
	 */
	public boolean removeAttribute(int index) {
		return this.root.remove(this.root.attribute(index));
	}

	/**
	 * 删除所有属性
	 * 
	 */
	public void removeAllAttribute() {
		List list = new ArrayList();
		Iterator it = this.root.attributeIterator();
		while (it.hasNext()) {
			list.add(it.next());
		}
		for (int i = 0; i < list.size(); i++) {
			this.root.remove((Attribute) list.get(i));
		}
	}

	/**
	 * 返回XML元素文本形式
	 */
	public String toString() {
		// TODO Auto-generated method stub
		if (this.root != null) {
			return XMLUtils.toXMLString(this.root, "gb2312");
		}
		return null;
	}

	/**
	 * 返回XML文档文本形式
	 */
	public String toXMLString() {
		if (this.node != null) {
			return XMLUtils.toXMLString(this.node, "gb2312");
		}
		return null;
	}

	/**
	 * 生成到xml文件
	 * 
	 * @param fileNamePath
	 *            目标XML文件路径名 void
	 * @date 2008-3-13
	 * @package com.etone.dao.vo
	 */
	public void toFile(String fileNamePath) {
		try {
			/*
			 * OutputFormat format = OutputFormat.createPrettyPrint();
			 * format.setEncoding("gb2312"); XMLWriter writer = new
			 * XMLWriter(new FileWriter(fileNamePath), format );
			 * writer.write(this.node); writer.close();
			 */
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			FileOutputStream fos = new FileOutputStream(new File(fileNamePath));
			// XMLWriter writer = new XMLWriter(new FileWriter(fileNamePath),
			// format );
			XMLWriter writer = new XMLWriter(fos, format);
			writer.write(this.node);
			writer.close();
		} catch (IOException ex) {
			System.out.println("生成xml文件时出错." + fileNamePath);
			ex.printStackTrace();
		}
	}

	public Document getNode() {
		return node;
	}

	public void setNode(Document node) {
		this.node = node;
		this.root = this.node.getRootElement();
		this.parent = this.node.getParent();
	}

	public Element getParent() {
		return parent;
	}

	public void setParent(Element parent) {
		this.parent = parent;
	}

	public Element getRoot() {
		return root;
	}

	public void setRoot(Element root) {
		this.root = root;
	}

	public List getSubNodes() {
		return subNodes;
	}

	public String getFdcDefaultValue() {
		return fdcDefaultValue;
	}

	public void setFdcDefaultValue(String fdcDefaultValue) {
		this.fdcDefaultValue = fdcDefaultValue;
	}

	public String getFddDefaultValue() {
		return fddDefaultValue;
	}

	public void setFddDefaultValue(String fddDefaultValue) {
		this.fddDefaultValue = fddDefaultValue;
	}

	public String getFdiDefaultValue() {
		return fdiDefaultValue;
	}

	public void setFdiDefaultValue(String fdiDefaultValue) {
		this.fdiDefaultValue = fdiDefaultValue;
	}

	/**
	 * 删除原有子结点,再增加新结点
	 * 
	 * @param subNodes
	 */
	public void setSubNodes(List subNodes) {
		if (subNodes == null) {
			return;
		}
		Iterator it = this.root.elementIterator();
		while (it.hasNext()) {
			this.root.remove((Element) it.next());
		}

		this.subNodes = subNodes;
		it = subNodes.iterator();
		while (it.hasNext()) {
			Element e = (Element) ((CacheNodeVO) it.next()).getRoot();
			this.root.add(e);
		}
	}

	/**
	 * 增加子结点
	 * 
	 * @param subNodes
	 */
	public void addSubNodes(List subNodes) {
		if (subNodes == null) {
			return;
		}
		Iterator it = subNodes.iterator();
		while (it.hasNext()) {
			CacheNodeVO mapVo = (CacheNodeVO) it.next();
			this.subNodes.add(mapVo);
			Element e = (Element) mapVo.getRoot();
			this.root.add(e);
		}
	}

	/**
	 * 增加子结点
	 * 
	 * @param subNodes
	 */
	public void addSubNode(CacheNodeVO subNode) {
		this.subNodes.add(subNode);
		this.root.add(subNode.getRoot());
	}

	public static void main(String[] args) {

		CacheNodeVO mapVo = new CacheNodeVO("Data");
		mapVo.addAttribute("version", "1.1");
		mapVo.addAttribute("name", "flash map data");
		mapVo.addAttribute("time", "2008-01-01");

		CacheNodeVO mapVo1 = new CacheNodeVO("Rtds");
		mapVo1.addAttribute("fdiId", "1");
		mapVo1.addAttribute("name", "RTD1");
		mapVo1.addAttribute("time", "2008-01-01");

		CacheNodeVO mapVo2 = new CacheNodeVO("Rtds");
		mapVo2.addAttribute("fdiId", "2");
		mapVo2.addAttribute("name", "RTD2");
		mapVo2.addAttribute("time", "2008-01-01");

		CacheNodeVO mapVo3 = new CacheNodeVO("Rtds");
		mapVo3.addAttribute("fdiId", "2");
		mapVo3.addAttribute("name", "RTD2");
		mapVo3.addAttribute("time", "2008-01-01");

		List subNodes = new ArrayList();
		subNodes.add(mapVo1);
		subNodes.add(mapVo2);
		subNodes.add(mapVo3);
		mapVo.setSubNodes(subNodes);
		mapVo.setSubNodes(subNodes);
		// 写入文件
		mapVo.toFile("C:/test.xml");
		System.out.println("-----------");
		System.out.println(mapVo.toXMLString());
		// 读取
		CacheNodeVO cnv = new CacheNodeVO();
		cnv.setNode(XMLUtils.read("C:/test.xml"));
		Element root = cnv.getRoot();//获取根节点
		List nodes = root.elements("test");//获取根节点下的所有test节点

	}


}

 

import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;

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工具类
 * 
 * @author kstrive
 * @since 2008-01-02
 */
public class XMLUtils {

	/**
	 * 返回格式化的XML字段串
	 * 
	 * @param document
	 *            要格式化的文档
	 * @param encoding
	 *            使用的编码,如果为null刚使用默认编码(gb2312)
	 * @return 格式化的XML字段串
	 */
	public static String toXMLString(Document document, String encoding) {
		if (encoding == null) {
			encoding = "gb2312";
		}
		StringWriter writer = new StringWriter();
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("gb2312");
		XMLWriter xmlwriter = new XMLWriter(writer, format);
		try {
			xmlwriter.write(document);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return writer.toString();
	}

	/**
	 * 返回格式化的XML字段串
	 * 
	 * @param element
	 *            要格式化的节点元素
	 * @param encoding
	 *            使用的编码,如果为null刚使用默认编码(gb2312)
	 * @return 格式化的XML字段串
	 */
	public static String toXMLString(Element element, String encoding) {
		if (encoding == null) {
			encoding = "gb2312";
		}
		StringWriter writer = new StringWriter();
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding(encoding);
		XMLWriter xmlwriter = new XMLWriter(writer, format);
		try {
			xmlwriter.write(element);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return writer.toString();
	}

	/**
	 * 格式化文档并输出到文件
	 * 
	 * @param document
	 *            要输出的文档
	 * @param filename
	 *            XML文件名
	 * @param encoding
	 *            使用的编码,如果为null刚使用默认编码(gb2312)
	 * @return true or false
	 */
	public static boolean toXMLFile(Document document, String filename,
			String encoding) {
		if (encoding == null) {
			encoding = "gb2312";
		}
		boolean returnValue = false;
		try {
			XMLWriter output = null;
			/** 格式化输出,类型IE浏览一样 */
			OutputFormat format = OutputFormat.createPrettyPrint();
			/** 指定XML字符集编码 */
			format.setEncoding(encoding);
			output = new XMLWriter(new FileWriter(new File(filename)), format);
			output.write(document);
			output.close();
			/** 执行成功,需返回1 */
			returnValue = true;
		} catch (Exception ex) {
			ex.printStackTrace();
			returnValue = false;
		}
		return returnValue;
	}

	/**
	 * 格式化XML文件并保存
	 * 
	 * @param srcFileName
	 *            源XML文件
	 * @param desFileName
	 *            格式化后的XML文件,如果为null,则使用srcFileName
	 * @param encoding
	 *            使用的编码,如果为null刚使用默认编码(gb2312)
	 * @return true or false
	 */
	public static boolean toXMLFile(String srcFileName, String desFileName,
			String encoding) {
		if (encoding == null) {
			encoding = "gb2312";
		}
		if (desFileName == null) {
			desFileName = srcFileName;
		}
		boolean returnValue = false;
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(new File(srcFileName));
			XMLWriter output = null;
			/** 格式化输出,类型IE浏览一样 */
			OutputFormat format = OutputFormat.createPrettyPrint();
			/** 指定XML字符集编码 */
			format.setEncoding(encoding);
			output = new XMLWriter(new FileWriter(new File(desFileName)),
					format);
			output.write(document);
			output.close();
			/** 执行成功,需返回1 */
			returnValue = true;
		} catch (Exception ex) {
			ex.printStackTrace();
			returnValue = false;
		}
		return returnValue;
	}

	/**
	 * 从读取XML文件
	 * 
	 * @param fileName
	 * @return Document对象
	 */
	public static Document read(String fileName) {
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			document = reader.read(new File(fileName));
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return document;
	}

	/**
	 * 从XML字符串转换到document
	 * 
	 * @param xmlStr
	 *            XML字符串
	 * @return Document
	 */
	public static Document parseText(String xmlStr) {
		Document document = null;
		try {
			document = DocumentHelper.parseText(xmlStr);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return document;
	}
}