在用java操作xml文档时,好像很少用到jdk中sun提供的方法,因为它的实现比较繁琐,而经常使用的是jdom为我们提供的类库。
1、jdom的下载地址,[url]http://www.jdom.org/downloads/source.html[/url]
2、把/lib中的所有jar,以及bulid中的jdom.jar 复制到项目的lib目录下即可。
3、在src目录下建立一个xml文件例如:applicationCntext.xml
内容如下:
4、编写单元测试类(引入junit.jar)
如下:
运行结果:com.mysql.jdbc.Driver
[color=red]对xml的写操作[url]http://cheney-mydream.iteye.com/admin/blogs/403218[/url][/color]
1、jdom的下载地址,[url]http://www.jdom.org/downloads/source.html[/url]
2、把/lib中的所有jar,以及bulid中的jdom.jar 复制到项目的lib目录下即可。
3、在src目录下建立一个xml文件例如:applicationCntext.xml
内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="DataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/assgnment</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>root</value>
</property>
</bean>
</beans>
4、编写单元测试类(引入junit.jar)
如下:
package cn.edu.ujn.test;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
public class ReadXml extends TestCase{
/*
Builds a JDOM document from files, streams, readers, URLs,
or a SAX InputSource instance using a SAX parser
*/
public void testRead(){
SAXBuilder sb = new SAXBuilder();
// 得到要操作的xml文档对象
Document document = null;
try {
document = sb.build(this.getClass().getClassLoader().getResourceAsStream("applicationContext.xml"));
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 得到xml 中的所有element,我们所得到的所有节点都是element对像
Element rootEle = document.getRootElement();
//得到子节点
Element child = null;
try {
child = (Element)XPath.selectSingleNode(rootEle, "//beans/bean/property/value");
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(child.getText());
}
}
运行结果:com.mysql.jdbc.Driver
[color=red]对xml的写操作[url]http://cheney-mydream.iteye.com/admin/blogs/403218[/url][/color]