自定義簡單XML的讀與存,便捷工具類

 
Java代碼 複製代碼 收藏代碼

 

主要依賴jar包dom4j.jar ,main方法中有使用方法
Java代碼 複製代碼 收藏代碼
  1. import java.io.Serializable;   
  2. import java.util.HashMap;   
  3. import java.util.Iterator;   
  4. import java.util.Map;   
  5.   
  6. /**  
  7.  * XML數據元素操作基類  
  8.  *   
  9.  * @author Administrator  
  10.  *   
  11.  */  
  12. public class CacheNodeBaseVO implements Serializable {   
  13.     /**  
  14.      *   
  15.      */  
  16.     private static final long serialVersionUID = 3821539085598864455L;   
  17.   
  18.     // 參數傳遞   
  19.     protected HashMap<String,Object> parameters = null;   
  20.   
  21.     public CacheNodeBaseVO() {   
  22.         this.parameters = new HashMap<String, Object>();   
  23.     }   
  24.        
  25.     /**  
  26.      * 加參數  
  27.      */  
  28.     public void addParam(String name, Object value) {   
  29.         this.parameters.put(name, value);   
  30.     }   
  31.   
  32.     /**  
  33.      * 增加加參數  
  34.      *   
  35.      * @param map  
  36.      */  
  37.     public void addParam(Map map) {   
  38.         if(map==null || map.size()<=0){   
  39.             return;   
  40.         }   
  41.         Iterator it = map.keySet().iterator();   
  42.         while (it.hasNext()) {   
  43.             String key = String.valueOf(it.next());            
  44.             Object value = map.get(key);   
  45.             addParam(key, value);   
  46.         }   
  47.     }   
  48.   
  49.     /**  
  50.      * 刪除參數  
  51.      *   
  52.      * @param key  
  53.      */  
  54.     public void removeParam(String key) {   
  55.         this.parameters.remove(key);   
  56.     }   
  57.   
  58.     public void removeAllParams() {   
  59.         this.parameters.clear();   
  60.     }   
  61.   
  62.     public String getParam(String key) {   
  63.         return (String) this.parameters.get(key);   
  64.     }   
  65.        
  66.     public Object getParamObj(String key) {   
  67.         return this.parameters.get(key);   
  68.     }   
  69.   
  70.     public HashMap<String,Object> getParameters() {   
  71.         return parameters;   
  72.     }   
  73.   
  74.     public void setParameters(HashMap parameters) {   
  75.         this.parameters = parameters;   
  76.     }   
  77.   
  78.     public String toString() {   
  79.         StringBuffer sb = new StringBuffer();   
  80.         Iterator it = this.parameters.keySet().iterator();   
  81.         while (it.hasNext()) {   
  82.             String key = (String) it.next();   
  83.             sb.append(key + ":" + this.parameters.get(key) + ";");   
  84.         }   
  85.         return sb.toString();   
  86.     }   
  87.        
  88.     public static void main(String[] args) {   
  89.         CacheNodeBaseVO vo = new CacheNodeBaseVO();   
  90.         vo.addParam("fdiId","22");   
  91.         vo.addParam("fdiId2","22");   
  92.         vo.addParam("fdiId3","22");   
  93.         vo.addParam("fdiId4","22");   
  94.         vo.addParam("fdiId5","22");   
  95.         System.out.println(vo.toString());   
  96.            
  97.     }   
  98. }  
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());
		
	}
}

 

Java代碼 複製代碼 收藏代碼
  1. import java.io.File;   
  2. import java.io.FileOutputStream;   
  3. import java.io.IOException;   
  4. import java.io.Serializable;   
  5. import java.util.ArrayList;   
  6. import java.util.HashMap;   
  7. import java.util.Iterator;   
  8. import java.util.List;   
  9.   
  10. import org.dom4j.Attribute;   
  11. import org.dom4j.Document;   
  12. import org.dom4j.DocumentHelper;   
  13. import org.dom4j.Element;   
  14. import org.dom4j.io.OutputFormat;   
  15. import org.dom4j.io.XMLWriter;   
  16.   
  17. import com.etone.util.XMLUtils;   
  18.   
  19. /**  
  20.  * XML數據元素操作基類  
  21.  *   
  22.  * @author Administrator  
  23.  *   
  24.  */  
  25. public class CacheNodeVO extends CacheNodeBaseVO implements Serializable {   
  26.     /**  
  27.      *   
  28.      */  
  29.     private static final long serialVersionUID = 3821539085598864455L;   
  30.   
  31.     private Document node = null;   
  32.   
  33.     private Element root = null;   
  34.   
  35.     private List subNodes = null;   
  36.   
  37.     private Element parent = null;   
  38.   
  39.     // fdc屬性爲null時的默認值   
  40.     private String fdcDefaultValue = "";   
  41.   
  42.     // fdi屬性爲null時的默認值   
  43.     private String fdiDefaultValue = "0";   
  44.   
  45.     // fdd屬性爲null時的默認值   
  46.     private String fddDefaultValue = "00:00";   
  47.   
  48.     /**  
  49.      * 構造方法,root名稱爲"root"  
  50.      *   
  51.      */  
  52.     public CacheNodeVO() {   
  53.         this("Node");   
  54.     }   
  55.   
  56.     /**  
  57.      * 構造方法  
  58.      *   
  59.      * @param rootName  
  60.      *            根據元素名  
  61.      */  
  62.     public CacheNodeVO(String rootName) {   
  63.         this.node = DocumentHelper.createDocument();   
  64.         this.root = this.node.addElement(rootName);   
  65.         this.subNodes = new ArrayList();   
  66.         this.parent = this.node.getParent();   
  67.     }   
  68.   
  69.     /**  
  70.      * 修改本結果的name  
  71.      *   
  72.      * @param name  
  73.      */  
  74.     public void setNodeName(String name) {   
  75.         this.root.setName(name);   
  76.     }   
  77.   
  78.     /**  
  79.      * 把屬性加到本節點元素中  
  80.      */  
  81.     public Element addAttribute(String name, String value) {   
  82.         if (name == null) {   
  83.             return null;   
  84.         }   
  85.         if (value == null) {   
  86.             if (name.startsWith("fdi")) {   
  87.                 value = fdiDefaultValue;   
  88.             } else if (name.startsWith("fdc")) {   
  89.                 value = fdcDefaultValue;   
  90.             } else if (name.startsWith("fdd")) {   
  91.                 value = fddDefaultValue;   
  92.             } else  
  93.                 value = "-";   
  94.         }   
  95.         return this.root.addAttribute(name, value);   
  96.     }   
  97.   
  98.     /**  
  99.      * 取屬性值  
  100.      *   
  101.      * @param name  
  102.      * @return String  
  103.      * @date 2008-3-20  
  104.      * @package com.etone.dao.vo  
  105.      */  
  106.     public String getAttribute(String name) {   
  107.         return this.root.attributeValue(name);   
  108.     }   
  109.   
  110.     /**  
  111.      * 把屬性加到本節點元素中  
  112.      */  
  113.     public Element addAttribute(Attribute attribute) {   
  114.         this.root.add(attribute);   
  115.         return root;   
  116.     }   
  117.   
  118.     /**  
  119.      * 從本節點元素中移除某指定屬性  
  120.      */  
  121.     public boolean removeAttribute(String key) {   
  122.         return this.root.remove(this.root.attribute(key));   
  123.     }   
  124.   
  125.     /**  
  126.      * 從本節點元素中移除某指定屬性  
  127.      */  
  128.     public boolean removeAttribute(int index) {   
  129.         return this.root.remove(this.root.attribute(index));   
  130.     }   
  131.   
  132.     /**  
  133.      * 刪除所有屬性  
  134.      *   
  135.      */  
  136.     public void removeAllAttribute() {   
  137.         List list = new ArrayList();   
  138.         Iterator it = this.root.attributeIterator();   
  139.         while (it.hasNext()) {   
  140.             list.add(it.next());   
  141.         }   
  142.         for (int i = 0; i < list.size(); i++) {   
  143.             this.root.remove((Attribute) list.get(i));   
  144.         }   
  145.     }   
  146.   
  147.     /**  
  148.      * 返回XML元素文本形式  
  149.      */  
  150.     public String toString() {   
  151.         // TODO Auto-generated method stub  
  152.         if (this.root != null) {   
  153.             return XMLUtils.toXMLString(this.root, "gb2312");   
  154.         }   
  155.         return null;   
  156.     }   
  157.   
  158.     /**  
  159.      * 返回XML文檔文本形式  
  160.      */  
  161.     public String toXMLString() {   
  162.         if (this.node != null) {   
  163.             return XMLUtils.toXMLString(this.node, "gb2312");   
  164.         }   
  165.         return null;   
  166.     }   
  167.   
  168.     /**  
  169.      * 生成到xml文件  
  170.      *   
  171.      * @param fileNamePath  
  172.      *            目標XML文件路徑名 void  
  173.      * @date 2008-3-13  
  174.      * @package com.etone.dao.vo  
  175.      */  
  176.     public void toFile(String fileNamePath) {   
  177.         try {   
  178.             /*  
  179.              * OutputFormat format = OutputFormat.createPrettyPrint(); 
  180.              * format.setEncoding("gb2312"); XMLWriter writer = new 
  181.              * XMLWriter(new FileWriter(fileNamePath), format ); 
  182.              * writer.write(this.node); writer.close(); 
  183.              */  
  184.             OutputFormat format = OutputFormat.createPrettyPrint();   
  185.             format.setEncoding("UTF-8");   
  186.             FileOutputStream fos = new FileOutputStream(new File(fileNamePath));   
  187.             // XMLWriter writer = new XMLWriter(new FileWriter(fileNamePath),  
  188.             // format );   
  189.             XMLWriter writer = new XMLWriter(fos, format);   
  190.             writer.write(this.node);   
  191.             writer.close();   
  192.         } catch (IOException ex) {   
  193.             System.out.println("生成xml文件時出錯." + fileNamePath);   
  194.             ex.printStackTrace();   
  195.         }   
  196.     }   
  197.   
  198.     public Document getNode() {   
  199.         return node;   
  200.     }   
  201.   
  202.     public void setNode(Document node) {   
  203.         this.node = node;   
  204.         this.root = this.node.getRootElement();   
  205.         this.parent = this.node.getParent();   
  206.     }   
  207.   
  208.     public Element getParent() {   
  209.         return parent;   
  210.     }   
  211.   
  212.     public void setParent(Element parent) {   
  213.         this.parent = parent;   
  214.     }   
  215.   
  216.     public Element getRoot() {   
  217.         return root;   
  218.     }   
  219.   
  220.     public void setRoot(Element root) {   
  221.         this.root = root;   
  222.     }   
  223.   
  224.     public List getSubNodes() {   
  225.         return subNodes;   
  226.     }   
  227.   
  228.     public String getFdcDefaultValue() {   
  229.         return fdcDefaultValue;   
  230.     }   
  231.   
  232.     public void setFdcDefaultValue(String fdcDefaultValue) {   
  233.         this.fdcDefaultValue = fdcDefaultValue;   
  234.     }   
  235.   
  236.     public String getFddDefaultValue() {   
  237.         return fddDefaultValue;   
  238.     }   
  239.   
  240.     public void setFddDefaultValue(String fddDefaultValue) {   
  241.         this.fddDefaultValue = fddDefaultValue;   
  242.     }   
  243.   
  244.     public String getFdiDefaultValue() {   
  245.         return fdiDefaultValue;   
  246.     }   
  247.   
  248.     public void setFdiDefaultValue(String fdiDefaultValue) {   
  249.         this.fdiDefaultValue = fdiDefaultValue;   
  250.     }   
  251.   
  252.     /**  
  253.      * 刪除原有子結點,再增加新結點  
  254.      *   
  255.      * @param subNodes  
  256.      */  
  257.     public void setSubNodes(List subNodes) {   
  258.         if (subNodes == null) {   
  259.             return;   
  260.         }   
  261.         Iterator it = this.root.elementIterator();   
  262.         while (it.hasNext()) {   
  263.             this.root.remove((Element) it.next());   
  264.         }   
  265.   
  266.         this.subNodes = subNodes;   
  267.         it = subNodes.iterator();   
  268.         while (it.hasNext()) {   
  269.             Element e = (Element) ((CacheNodeVO) it.next()).getRoot();   
  270.             this.root.add(e);   
  271.         }   
  272.     }   
  273.   
  274.     /**  
  275.      * 增加子結點  
  276.      *   
  277.      * @param subNodes  
  278.      */  
  279.     public void addSubNodes(List subNodes) {   
  280.         if (subNodes == null) {   
  281.             return;   
  282.         }   
  283.         Iterator it = subNodes.iterator();   
  284.         while (it.hasNext()) {   
  285.             CacheNodeVO mapVo = (CacheNodeVO) it.next();   
  286.             this.subNodes.add(mapVo);   
  287.             Element e = (Element) mapVo.getRoot();   
  288.             this.root.add(e);   
  289.         }   
  290.     }   
  291.   
  292.     /**  
  293.      * 增加子結點  
  294.      *   
  295.      * @param subNodes  
  296.      */  
  297.     public void addSubNode(CacheNodeVO subNode) {   
  298.         this.subNodes.add(subNode);   
  299.         this.root.add(subNode.getRoot());   
  300.     }   
  301.   
  302.     public static void main(String[] args) {   
  303.   
  304.         CacheNodeVO mapVo = new CacheNodeVO("Data");   
  305.         mapVo.addAttribute("version""1.1");   
  306.         mapVo.addAttribute("name""flash map data");   
  307.         mapVo.addAttribute("time""2008-01-01");   
  308.   
  309.         CacheNodeVO mapVo1 = new CacheNodeVO("Rtds");   
  310.         mapVo1.addAttribute("fdiId""1");   
  311.         mapVo1.addAttribute("name""RTD1");   
  312.         mapVo1.addAttribute("time""2008-01-01");   
  313.   
  314.         CacheNodeVO mapVo2 = new CacheNodeVO("Rtds");   
  315.         mapVo2.addAttribute("fdiId""2");   
  316.         mapVo2.addAttribute("name""RTD2");   
  317.         mapVo2.addAttribute("time""2008-01-01");   
  318.   
  319.         CacheNodeVO mapVo3 = new CacheNodeVO("Rtds");   
  320.         mapVo3.addAttribute("fdiId""2");   
  321.         mapVo3.addAttribute("name""RTD2");   
  322.         mapVo3.addAttribute("time""2008-01-01");   
  323.   
  324.         List subNodes = new ArrayList();   
  325.         subNodes.add(mapVo1);   
  326.         subNodes.add(mapVo2);   
  327.         subNodes.add(mapVo3);   
  328.         mapVo.setSubNodes(subNodes);   
  329.         mapVo.setSubNodes(subNodes);   
  330.         // 寫入文件   
  331.         mapVo.toFile("C:/test.xml");   
  332.         System.out.println("-----------");   
  333.         System.out.println(mapVo.toXMLString());   
  334.         // 讀取   
  335.         CacheNodeVO cnv = new CacheNodeVO();   
  336.         cnv.setNode(XMLUtils.read("C:/test.xml"));   
  337.         Element root = cnv.getRoot();//獲取根節點  
  338.         List nodes = root.elements("test");//獲取根節點下的所有test節點  
  339.   
  340.     }   
  341.   
  342.   
  343. }  
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節點

	}


}

 

Java代碼 複製代碼 收藏代碼
  1. import java.io.File;   
  2. import java.io.FileWriter;   
  3. import java.io.StringWriter;   
  4.   
  5. import org.dom4j.Document;   
  6. import org.dom4j.DocumentException;   
  7. import org.dom4j.DocumentHelper;   
  8. import org.dom4j.Element;   
  9. import org.dom4j.io.OutputFormat;   
  10. import org.dom4j.io.SAXReader;   
  11. import org.dom4j.io.XMLWriter;   
  12.   
  13. /**  
  14.  * XML工具類  
  15.  *   
  16.  * @author kstrive  
  17.  * @since 2008-01-02  
  18.  */  
  19. public class XMLUtils {   
  20.   
  21.     /**  
  22.      * 返回格式化的XML字段串  
  23.      *   
  24.      * @param document  
  25.      *            要格式化的文檔  
  26.      * @param encoding  
  27.      *            使用的編碼,如果爲null剛使用默認編碼(gb2312)  
  28.      * @return 格式化的XML字段串  
  29.      */  
  30.     public static String toXMLString(Document document, String encoding) {   
  31.         if (encoding == null) {   
  32.             encoding = "gb2312";   
  33.         }   
  34.         StringWriter writer = new StringWriter();   
  35.         OutputFormat format = OutputFormat.createPrettyPrint();   
  36.         format.setEncoding("gb2312");   
  37.         XMLWriter xmlwriter = new XMLWriter(writer, format);   
  38.         try {   
  39.             xmlwriter.write(document);   
  40.         } catch (Exception e) {   
  41.             e.printStackTrace();   
  42.         }   
  43.         return writer.toString();   
  44.     }   
  45.   
  46.     /**  
  47.      * 返回格式化的XML字段串  
  48.      *   
  49.      * @param element  
  50.      *            要格式化的節點元素  
  51.      * @param encoding  
  52.      *            使用的編碼,如果爲null剛使用默認編碼(gb2312)  
  53.      * @return 格式化的XML字段串  
  54.      */  
  55.     public static String toXMLString(Element element, String encoding) {   
  56.         if (encoding == null) {   
  57.             encoding = "gb2312";   
  58.         }   
  59.         StringWriter writer = new StringWriter();   
  60.         OutputFormat format = OutputFormat.createPrettyPrint();   
  61.         format.setEncoding(encoding);   
  62.         XMLWriter xmlwriter = new XMLWriter(writer, format);   
  63.         try {   
  64.             xmlwriter.write(element);   
  65.         } catch (Exception e) {   
  66.             e.printStackTrace();   
  67.         }   
  68.         return writer.toString();   
  69.     }   
  70.   
  71.     /**  
  72.      * 格式化文檔並輸出到文件  
  73.      *   
  74.      * @param document  
  75.      *            要輸出的文檔  
  76.      * @param filename  
  77.      *            XML文件名  
  78.      * @param encoding  
  79.      *            使用的編碼,如果爲null剛使用默認編碼(gb2312)  
  80.      * @return true or false  
  81.      */  
  82.     public static boolean toXMLFile(Document document, String filename,   
  83.             String encoding) {   
  84.         if (encoding == null) {   
  85.             encoding = "gb2312";   
  86.         }   
  87.         boolean returnValue = false;   
  88.         try {   
  89.             XMLWriter output = null;   
  90.             /** 格式化輸出,類型IE瀏覽一樣 */  
  91.             OutputFormat format = OutputFormat.createPrettyPrint();   
  92.             /** 指定XML字符集編碼 */  
  93.             format.setEncoding(encoding);   
  94.             output = new XMLWriter(new FileWriter(new File(filename)), format);   
  95.             output.write(document);   
  96.             output.close();   
  97.             /** 執行成功,需返回1 */  
  98.             returnValue = true;   
  99.         } catch (Exception ex) {   
  100.             ex.printStackTrace();   
  101.             returnValue = false;   
  102.         }   
  103.         return returnValue;   
  104.     }   
  105.   
  106.     /**  
  107.      * 格式化XML文件並保存  
  108.      *   
  109.      * @param srcFileName  
  110.      *            源XML文件  
  111.      * @param desFileName  
  112.      *            格式化後的XML文件,如果爲null,則使用srcFileName 
  113.      * @param encoding  
  114.      *            使用的編碼,如果爲null剛使用默認編碼(gb2312)  
  115.      * @return true or false  
  116.      */  
  117.     public static boolean toXMLFile(String srcFileName, String desFileName,   
  118.             String encoding) {   
  119.         if (encoding == null) {   
  120.             encoding = "gb2312";   
  121.         }   
  122.         if (desFileName == null) {   
  123.             desFileName = srcFileName;   
  124.         }   
  125.         boolean returnValue = false;   
  126.         try {   
  127.             SAXReader saxReader = new SAXReader();   
  128.             Document document = saxReader.read(new File(srcFileName));   
  129.             XMLWriter output = null;   
  130.             /** 格式化輸出,類型IE瀏覽一樣 */  
  131.             OutputFormat format = OutputFormat.createPrettyPrint();   
  132.             /** 指定XML字符集編碼 */  
  133.             format.setEncoding(encoding);   
  134.             output = new XMLWriter(new FileWriter(new File(desFileName)),   
  135.                     format);   
  136.             output.write(document);   
  137.             output.close();   
  138.             /** 執行成功,需返回1 */  
  139.             returnValue = true;   
  140.         } catch (Exception ex) {   
  141.             ex.printStackTrace();   
  142.             returnValue = false;   
  143.         }   
  144.         return returnValue;   
  145.     }   
  146.   
  147.     /**  
  148.      * 從讀取XML文件  
  149.      *   
  150.      * @param fileName  
  151.      * @return Document對象  
  152.      */  
  153.     public static Document read(String fileName) {   
  154.         SAXReader reader = new SAXReader();   
  155.         Document document = null;   
  156.         try {   
  157.             document = reader.read(new File(fileName));   
  158.         } catch (DocumentException e) {   
  159.             // TODO Auto-generated catch block  
  160.             e.printStackTrace();   
  161.         }   
  162.         return document;   
  163.     }   
  164.   
  165.     /**  
  166.      * 從XML字符串轉換到document  
  167.      *   
  168.      * @param xmlStr  
  169.      *            XML字符串  
  170.      * @return Document  
  171.      */  
  172.     public static Document parseText(String xmlStr) {   
  173.         Document document = null;   
  174.         try {   
  175.             document = DocumentHelper.parseText(xmlStr);   
  176.         } catch (DocumentException e) {   
  177.             // TODO Auto-generated catch block  
  178.             e.printStackTrace();   
  179.         }   
  180.         return document;   
  181.     }   
  182. }  
發佈了5 篇原創文章 · 獲贊 2 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章