java 代码
- import java.io.*;
- import java.util.*;
- import javax.xml.XMLConstants;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.transform.Source;
- import javax.xml.transform.dom.DOMSource;
- import javax.xml.transform.stream.StreamSource;
- import javax.xml.validation.Schema;
- import javax.xml.validation.SchemaFactory;
- import javax.xml.validation.Validator;
- import org.dom4j.*;
- import org.dom4j.io.*;
- import org.xml.sax.SAXException;
- /**
- * name:XMLUtil.java
- *
- * desc: 本类是xml文档操作实用类,提供对xml文档操作的常用方法。
- *
- */
- public class XMLUtil
- {
- private Document doc;
- /**
- * 构造函数
- *
- */
- public XMLUtil()
- {
- }
- /**
- * 方法完成xml文件的加载,在调用本类的其他方法前需要调用loadFromFile()或者loadFromString()
- * @param file xml文件对象
- * @throws Exception
- */
- public void loadFromFile(File file)throws Exception
- {
- //参数无效
- if (file == null || !file.exists() || file.isDirectory())
- {
- throw new IllegalArgumentException("xml file is not valid!");
- }
- SAXReader saxReader = new SAXReader();
- doc = saxReader.read(file);
- }
- /**
- * 方法完成xml格式字符串的加载,转换成xml文档形式,注意参数必须符合xml格式,
- * 否则后续操作会出错
- * @param contents xml格式的字符串
- * @throws Exception
- */
- public void loadFromString(String contents)throws Exception
- {
- //参数无效
- if (contents == null || contents.trim().length() == 0)
- {
- throw new IllegalArgumentException("argument is not valid!");
- }
- doc = DocumentHelper.parseText(contents);
- }
- /**
- * 方法执行xml文档的保存
- * @param filePath xml文件保存路径
- * @param encoding xml文件编码格式(gb2312|utf-8|gbk等)
- * @throws IOException
- * @throws Exception
- */
- public void dump(String filePath, String encoding)throws IOException, Exception
- {
- //参数无效
- if (filePath == null || filePath.trim().length() == 0)
- {
- throw new IllegalArgumentException("store path is not valid!");
- }
- encoding = (encoding == null || encoding.trim().length() == 0) ? "gb2312" : encoding;
- OutputFormat format = OutputFormat.createPrettyPrint();
- format.setEncoding(encoding);
- format.setIndent(" ");
- FileWriter fileWriter = new FileWriter(filePath);
- XMLWriter xmlWriter = new XMLWriter(fileWriter, format);
- try
- {
- xmlWriter.write(doc);
- }
- catch(Exception e)
- {
- throw e;
- }
- finally
- {
- xmlWriter.close();
- xmlWriter = null;
- fileWriter.close();
- fileWriter = null;
- }
- }
- /**
- * 方法获取单个指定节点名的节点
- * @param name 节点名,支持Xpath
- * @param index 节点出现的索引位置
- * @return 找到返回Element,没找到返回null.
- * @throws Exception
- */
- public Element getElement(String name, int index)throws Exception
- {
- //节点名无效
- if (!isValidate(name))
- {
- throw new IllegalArgumentException("the element's name is not valid!");
- }
- //索引位置无效
- if (index < 0)
- {
- throw new IllegalArgumentException("the element's index is not valid!");
- }
- List elementsList = doc.selectNodes("//" + name);
- //指定的节点名存在并且索引有效
- if (elementsList != null && elementsList.size() > index)
- {
- return (Element)elementsList.get(index);
- }
- return null;
- }
- /**
- * 方法获取指定节点名的节点list
- * @param name 节点名
- * @return 节点list
- * @throws Exception
- */
- public ArrayList getElements(String name)throws Exception
- {
- //节点名无效
- if (!isValidate(name))
- {
- throw new IllegalArgumentException("element name is not valid!");
- }
- List list = doc.selectNodes("//" + name);
- ArrayList <Element>arrayList = new ArrayList<Element>();
- //存在节点时,循环获取每一个节点
- if (list != null)
- {
- int length = list.size();
- for (int i = 0; i < length; i++)
- {
- Node node = (Node)list.get(i);
- //节点是element实例时,添加到arrayList
- if (node instanceof Element)
- {
- arrayList.add((Element)node);
- }
- }
- }
- return arrayList;
- }
- /**
- * 方法获取一个节点的子节点信息
- * @param element 节点
- * @param subElementName 子节点名称
- * @return 子节点list,每个list元素是一个Element
- * @throws Exception
- */
- public ArrayList getSubElements(Element element, String subElementName)throws Exception
- {
- //参数无效
- if (element == null)
- {
- throw new IllegalArgumentException("element is null!");
- }
- //参数无效
- if (!isValidate(subElementName))
- {
- throw new IllegalArgumentException("sub element name is invalid!");
- }
- return (ArrayList)element.elements(subElementName);
- }
- /**
- * 方法获取单个节点值
- * @param name 节点名
- * @return 节点值
- * @throws Exception
- */
- public String getElementValue(String name)throws Exception
- {
- //invalid argument
- if (!isValidate(name))
- {
- throw new IllegalArgumentException("argument is not valid!");
- }
- Node node = doc.selectSingleNode("//" + name);
- //return the value
- if (node instanceof Element)
- {
- return node.getText().trim();
- }
- return "";
- }
- /**
- * 方法获取指定节点名的节点值的properties,重复的节点值将过滤掉
- * @param name 节点名
- * @return 节点值properties
- * @throws Exception
- */
- public Properties getElementValues(String name)throws Exception
- {
- if (!isValidate(name))
- {
- throw new IllegalArgumentException("elememt name is not valid!");
- }
- List elementList = doc.selectNodes("//" + name);
- Properties properties = new Properties();
- //节点存在
- if (elementList != null && elementList.size() > 0)
- {
- int length = elementList.size();
- for (int i = 0; i < length; i++)
- {
- String elementValue = ((Element)elementList.get(i)).getTextTrim();
- properties.put(elementValue, elementValue);
- }
- return properties;
- }
- return properties;
- }
- /**
- * 方法返回指定节点的属性信息
- * @param element 节点
- * @return 以name,value形式存在的属性
- * @throws Exception
- */
- public Properties getElementProperties(Element element)throws Exception
- {
- //参数无效
- if (element == null)
- {
- throw new IllegalArgumentException("element is null!");
- }
- List attributes = element.attributes();
- Properties properties = new Properties();
- for (int i = 0; i < attributes.size(); i++)
- {
- Attribute attr = (Attribute)attributes.get(i);
- properties.put(attr.getName(), attr.getValue());
- }
- return properties;
- }
- /**
- * 方法返回节点的属性信息
- * @param elementName 节点名称
- * @return 以name,value形式存在的属性
- * @throws Exception
- */
- public Properties getElementProperties(String elementName)throws Exception
- {
- //参数无效
- if (!isValidate(elementName))
- {
- throw new IllegalArgumentException("element name is invalid!");
- }
- return this.getElementProperties(this.getElement(elementName, 0));
- }
- /**
- * 方法执行节点名的更改
- * @param oldName 原始节点名
- * @param newName 更改后节点名
- * @param index 要更改的节点索引(索引指在xml文件中节点出现的位置)
- * @throws Exception
- */
- public void renameElement(String oldName, String newName, int index)throws Exception
- {
- //原始节点名无效
- if (!isValidate(oldName))
- {
- throw new IllegalArgumentException("original element name is not valid!");
- }
- //新的节点名无效
- if (!isValidate(newName))
- {
- throw new IllegalArgumentException("new element name is not valid!");
- }
- Element element = getElement(oldName, index);
- //指定的节点不存在
- if (element == null)
- {
- throw new Exception("can not find element, which name is : " + oldName
- + " index is : " + index);
- }
- element.setName(newName);
- }
- /**
- * 方法执行节点名的更改
- * @param oldName 原始节点名
- * @param newName 更改后节点名
- * @throws Exception
- */
- public void renameElements(String oldName, String newName)throws Exception
- {
- //原始节点名无效
- if (!isValidate(oldName))
- {
- throw new IllegalArgumentException("original element name is not valid!");
- }
- //新的节点名无效
- if (!isValidate(newName))
- {
- throw new IllegalArgumentException("new element name is not valid!");
- }
- ArrayList list = getElements(oldName);
- //不存在该节点名
- if (list == null)
- {
- throw new Exception("can not find any element, which name is : " + oldName);
- }
- //循环更改节点名
- int length = list.size();
- for (int i = 0; i < length; i++)
- {
- ((Element)list.get(i)).setName(newName);
- }
- }
- /**
- * 方法执行子节点的添加,要添加的子节点必须存在父节点,添加子节点的属性可以为空。
- * @param parent 父节点名
- * @param index 父节点的索引(存在同名父节点时,在第index个父节点处添加子节点)
- * @param current 子节点名
- * @param currentValue 子节点值
- * @param attributes 子节点属性
- * @throws Exception
- */
- public void addSubElement(String parent, int index, String current, String currentValue,
- Properties attributes)throws Exception
- {
- //父节点无效
- if (!isValidate(parent))
- {
- throw new IllegalArgumentException("parent element is not valid!");
- }
- //当前节点无效
- if (!isValidate(current))
- {
- throw new IllegalArgumentException("current element is not valid!");
- }
- Element parentElement = getElement(parent, index);
- //指定的父节点不存在
- if (parentElement == null)
- {
- throw new Exception("can not find the specified parent element, which name is :"
- + parent);
- }
- Element currentElement = parentElement.addElement(current);
- //节点值有效
- if (currentValue != null && currentValue.length() > 0)
- {
- currentElement.setText(currentValue);
- }
- //存在属性时,添加节点属性
- if (attributes != null)
- {
- Enumeration e = attributes.keys();
- while (e.hasMoreElements())
- {
- Object attrName = e.nextElement();
- Object attrValue = attributes.get(attrName);
- currentElement.addAttribute(attrName.toString(), attrValue.toString());
- }
- }
- }
- /**
- * 方法执行子节点的添加,要添加的子节点必须存在父节点,
- * @param parent 父节点名
- * @param index 父节点在xml文档中的索引
- * @param childList 子节点list,每个list元素是一个Element
- * @throws Exception
- */
- public void addSubElements(String parent, int index, ArrayList childList)
- throws Exception
- {
- Element parentElement = getElement(parent, index);
- //指定的父节点不存在