package com.test;
import java.io.File;
import java.io.FileWriter;
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.SAXReader;
import org.dom4j.io.XMLWriter;
public class Test {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String fileName = "E:\\persons.xml";
newFile(fileName);
readerAndEdit(fileName);
}
//新建一个文档
public static void newFile(String fileName){
Document doc = DocumentHelper.createDocument();
Element persons = doc.addElement("persons");
persons.addComment("这是xml的注释");
Element person1 = persons.addElement("person");
person1.addAttribute("sex", "男");
Element name1 = person1.addElement("name");
name1.setText("张三");
Element age1 =person1.addElement("age");
age1.setText("22");
try{
OutputFormat fmt = OutputFormat.createPrettyPrint();//IE : 可以不加
fmt.setEncoding("GBK"); //支持中文 : 可以不加
XMLWriter writer = new XMLWriter(new FileWriter(new File(fileName)),fmt); //或者 : new XMLWriter(new FileWriter(new File(fileName)))
writer.write(doc);
writer.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
//读文档进行修改
public static void readerAndEdit(String fileName) throws Exception{
SAXReader reader = new SAXReader();
Document doc = reader.read(new File(fileName));
List<Attribute> attList = doc.selectNodes("/persons/person/@sex ");
//修改性别
for(Attribute att : attList){
if("男".equals(att.getValue())){
att.setValue("女");
}
}
List<Element> personList = doc.selectNodes("/persons/person");
//添加元素
for(Element person : personList){
Element address = person.addElement("address");
address.setText("北京");
}
//删除元素
List<Element> list = doc.selectNodes("/persons/person");
for(Element person : list){
Iterator<Element> addList = person.elementIterator("address");
while(addList.hasNext()){
person.remove(addList.next());
}
}
OutputFormat fmt = OutputFormat.createPrettyPrint();
fmt.setEncoding("GBK");
XMLWriter writer = new XMLWriter(new FileWriter(new File(fileName)),fmt);
writer.write(doc);
writer.close();
}
}
-------------------------------------BaseRead 类
package cn.com.cncsi.product.ttms.common.distribute.parsexml;
import java.io.File;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import junit.framework.TestCase;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.sun.org.apache.bcel.internal.generic.GOTO;
/**
* 解析XML的基类
*
*/
public abstract class BaseRead {
/**
* 可以得到头部信息<Head>,以键值对的形式存储
*/
protected HashMap<String, String> headMP = new HashMap<String, String>();
/**
* 将List集合传成String时的分隔符
*/
protected String split = ";";
/**
* 根据文件名解析文件
* 例: C:\\web.xml
*/
protected Document testRead(String fileName){
try{
SAXReader reader = new SAXReader();
Document doc = reader.read(new File(fileName));
initHead(doc);
return doc;
}catch(Exception ex){
System.out.println("读取文件初始化头部Head错误");
// ex.printStackTrace();
}
return null;
}
/**
* 传入xml格式的字符串进行解析
* @param data
* @return
*/
protected Document readByString(String data){
try{
Document doc = DocumentHelper.parseText(data);
initHead(doc);
return doc;
}catch(Exception ex){
System.out.println("解析数据初始化头部Head错误");
// ex.printStackTrace();
}
return null;
}
/**
* 初始化所有xml的头部信息,并存入HashMap属性中.
* @param doc
*/
private void initHead(Document doc){
//读取head
List<Element> headElementList = doc.selectNodes("/ServiceContext/Head/property");
for(Element el : headElementList){
headMP.put(el.attributeValue("name"),el.attributeValue("value"));
}
}
/**
* 返回一个HashMap,用于保存xml文件的问信息(Head)
* @return
*/
public HashMap getHeadMP(){
return headMP;
}
/**
* 传入节点.将节点的值转换成Double类型
*/
protected double toDouble(Element e){
String temp = e.attributeValue("value");
try{
return Double.parseDouble(temp);
}catch(Exception ex){
System.out.println("转换Double类型出错");
// ex.printStackTrace();
}
return 0;
}
/**
* 传入节点.将节点的值转换成Timestamp类型
*/
protected Timestamp toTime(Element e){
String temp = e.attributeValue("value");
try{
return Timestamp.valueOf(temp);
}catch(Exception ex){
System.out.println("转换Timestamp类型出错");
// ex.printStackTrace();
}
return Timestamp.valueOf("2008-08-08 12:12:12");
}
/**
* 传入节点.将节点的值转换成long类型
*/
protected long toLong(Element e){
String temp = e.attributeValue("value");
try{
return Long.parseLong(temp);
}catch(Exception ex){
System.out.println("转换long类型出错");
// ex.printStackTrace();
}
return 0;
}
/**
* 传入节点.将节点的值转换成int类型
*/
protected int toInt(Element e){
String temp = e.attributeValue("value");
try{
return Integer.parseInt(temp);
}catch(Exception ex){
System.out.println("转换long类型出错");
// ex.printStackTrace();
}
return 0;
}
/**
* 传入节点.将节点的值转换成String类型
*/
protected String toValue(Element e){
return e.attributeValue("value");
}
/**
* 传入节点.得到节点的name属性的值
*/
protected String toName(Element e){
return e.attributeValue("name");
}
}
-----------------解析XML的类 extends BaseRead
Document doc = readByString(data); //data:xml格式的字符串
Element tTCommonOpElement = (Element) doc.selectNodes("/ServiceContext/TTCommonOp").get(0);
String nodeName;
String nameValue;
for(Element element : (List<Element>)tTCommonOpElement.elements()){
nodeName = element.getName();
nameValue = toName(element);
if("TT_Code".equalsIgnoreCase(nameValue)){
}else if("Operation".equalsIgnoreCase(nodeName)){
List<Element> opElement = element.elements();
String opNodeName ;
String opNameValue ;
for(Element el : opElement){
opNodeName = el.getName();
opNameValue = toName(el);
if("Operation_Id".equalsIgnoreCase(opNameValue)){
}else if("Operation_Name".equalsIgnoreCase(opNameValue)){
}else if("Operator".equalsIgnoreCase(opNodeName)){
List<Element> list = el.elements();
String orNameValue ;
for(Element e: list){
String eNameValue = e.attributeValue("name");
if("User_Id".equalsIgnoreCase(eNameValue)){
}else if("User_Name".equalsIgnoreCase(eNameValue)){
}else if("Zone_Code".equalsIgnoreCase(eNameValue)){
}
}
}else if("Operator_Dept".equalsIgnoreCase(opNodeName)){
List<Element> list = el.elements();
for(Element e : list){
String eNameValue = e.attributeValue("name");
if("Dept_Id".equalsIgnoreCase(eNameValue)){
}else if("Dept_Name".equalsIgnoreCase(eNameValue)){
}
}
}
}
}
}