dom4j学习笔记:动态创建和修改Spring的bean配置文件

    今天本来打算写Spring温故知新系列的第二篇,不过突然想起一直都忘了学怎么用java来操作XML,这么重要的事情居然拖了这么久才想起来实在是太不应该了,于是今天就先练习一下用dom4j来操作XML。

    其实dom4j这个库实在是太方便了,使用起来跟C#操作XML几乎没太大差别,也没什么难度,所以就先贴两段代码吧。

其中有几个要点:
1、如果只是创建一个XML文件,那么只需要导入dom4j-1.6.1.jar就可以了,路径如下:
spring-framework-2.5.6\lib\dom4j\dom4j-1.6.1.jar
如果是需要读取或者修改,那么就需要导入这个库内的另外一个文件:
spring-framework-2.5.6\lib\dom4j\jaxen-1.1-beta-7.jar
否则就会报错,报错内容如下:
java.lang.NoClassDefFoundError: org/jaxen/JaxenException
...
...
...

2、dom4j是支持链式操作的,这跟jQuery非常像。这样一来创建一个XML文件就非常方便而且代码结构看起来也更加清晰明了。

3、要学会XPath.... 要不然你会很痛苦,不过XPath其实很简单,应该花不了多少时间,难不住各位的,哈哈~


Action部分:
package com.iteye.bolide74.action;

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

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class MyDom4j {
	/**
	 * 动态创建一个bean配置文件,包含HelloWorld这个bean,并添加初始值
	 * */
	public void createXML(String xmlPath, String msg) throws IOException {
		Document XmlDoc = DocumentHelper.createDocument();
		XmlDoc.addDocType("beans", "-//SPRING//DTD BEAN//EN",
				"http://www.springframework.org/dtd/spring-beans.dtd");
		//首先创建beans根节点
		Element beansEle = XmlDoc.addElement("beans");
		
		//注意:dom4j是支持类似于jQuery一样的链式操作的
		Element beanHelloWorld = beansEle.addElement("bean")
				.addAttribute("id", "HelloWorld")
				.addAttribute("class", "com.iteye.bolide74.action.HelloWorld");
		Element propertyHelloWorld = beanHelloWorld.addElement("property")
				.addAttribute("name", "msg");
		Element valueHelloWorld = propertyHelloWorld.addElement("value")
				.addText(msg);
		XMLWriter outXml = new XMLWriter(new FileWriter(new File(xmlPath)));
		outXml.write(XmlDoc);
		outXml.close();
	}

	/**
	 * 首先遍历一个bean配置文件里的所有bean,获取id和class的值, 然后修改HelloWorld这个bean的msg的值
	 * @throws IOException 
	 * */
	public void editXML(String xmlPath, String msg) throws DocumentException, IOException {
		Document XmlDoc = new SAXReader().read(new File(xmlPath));
		List<Element> xmlList = XmlDoc.selectNodes("/beans/bean");
		System.out.println("\r\n遍历所有的bean获得id和class:");
		for (Element element : xmlList) {
			System.out.println("id:" + element.attributeValue("id")
					+ " / class:" + element.attributeValue("class"));
		}
		System.out.println("\r\n动态修改HelloWorld这个bean的msg值:");

//用XPath来获取单一节点
		Node valueHelloWorld = XmlDoc
				.selectSingleNode("/beans/bean[@id='HelloWorld']/property[@name='msg']/value");
		System.out.println("原始值为:" + valueHelloWorld.getText());
		valueHelloWorld.setText(msg);
		System.out.println("修改后的值为:" + valueHelloWorld.getText());
//修改完了以后记得保存,要不然你会纳闷为什么XML文件没变的,哈哈
		XMLWriter outXml = new XMLWriter(new FileWriter(new File(xmlPath)));
		outXml.write(XmlDoc);
		outXml.close();
	}
}


package com.iteye.bolide74.action;

public class HelloWorld {
	public String msg;

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
}


Tester实现类部分:
package com.iteye.bolide74.tester;

import java.io.IOException;

import org.dom4j.DocumentException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.iteye.bolide74.action.HelloWorld;
import com.iteye.bolide74.action.MyDom4j;

public class HelloWorldTester {
	public static void main(String[] args) {
		String xmlPath = "/WebContent/WEB-INF/conf/config_dom4j.xml";
		MyDom4j myBeans = new MyDom4j();
		try {
			myBeans.createXML(System.getProperty("user.dir") + xmlPath,
					"Hello,world!this is created by dom4j!");
		} catch (IOException e) {
			e.printStackTrace();
		}
		ApplicationContext ac = new FileSystemXmlApplicationContext(xmlPath);
		HelloWorld helloWorld = (HelloWorld) ac.getBean("HelloWorld");
		System.out.println(helloWorld.getMsg());
		try {
			myBeans.editXML(System.getProperty("user.dir") + xmlPath,
					"Hello,world!this is edited by dom4j!");
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 重新获取bean配置文件
		ac = new FileSystemXmlApplicationContext(xmlPath);
		helloWorld = (HelloWorld) ac.getBean("HelloWorld");
		System.out.println("\r\n" + helloWorld.getMsg());
	}
}


输出结果为:
Hello,world!this is created by dom4j!

遍历所有的bean获得id和class:
id:HelloWorld / class:com.iteye.bolide74.action.HelloWorld

动态修改HelloWorld这个bean的msg值:
原始值为:Hello,world!this is created by dom4j!
修改后的值为:Hello,world!this is edited by dom4j!

Hello,world!this is edited by dom4j!







你可能感兴趣的:(spring,jquery,xml,bean,ITeye)