dom4j读取xml总结

  dom4j是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件。

  操作xml的方式有四种,dom、sax、jdom、dom4j。dom4j性能最好,连Sun的JAXM也在用dom4j.目前许多开源项目中大量采用dom4j,例如Hibernate也用dom4j来读取XML配置文件。


下面是读取xml示例:

xml文件:

<span style="font-family:SimSun;font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<config>
	<db-info>
		<driver-name>oracle.jdbc.driver.OracleDriver</driver-name>
		<url>jdbc:oracle:thin:@localhost:1521:orcl</url>
		<user-name>drp</user-name>
		<password>drp</password>
	</db-info>
</config></span>

java读取方法:

<span style="font-family:SimSun;font-size:18px;">public class XmlConfigReader {
<span style="white-space:pre">	</span>//单例
<span style="white-space:pre">	</span>private static XmlConfigReader1 instance = null;
<span style="white-space:pre">	</span>private XmlConfigReader1(){


<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>public static synchronized XmlConfigReader1 getInstance() throws DocumentException {
<span style="white-space:pre">		</span>if (instance == null) {
<span style="white-space:pre">			</span>instance = new XmlConfigReader1();
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>return instance;
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>//读取xml的方法
<span style="white-space:pre">	</span>public String getDriverName() throws DocumentException{
<span style="white-space:pre">		</span>//读取xml
<span style="white-space:pre">		</span>SAXReader reader = new SAXReader();
<span style="white-space:pre">		</span>InputStream in = Thread.currentThread().getContextClassLoader()
<span style="white-space:pre">				</span>.getResourceAsStream("sys-config.xml");
<span style="white-space:pre">		</span>Document document = reader.read(in);
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>//读取xml的driver-name节点
<span style="white-space:pre">		</span>Element driverNameElt = (Element) document.selectObject("/config/db-info/driver-name");
<span style="white-space:pre">		</span>return driverNameElt.getStringValue();
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>
}</span>

调用XmlConfigReader的方法,读取xml的节点

<span style="font-family:SimSun;font-size:18px;">	public static void main(String[] args){
		try {
			System.out.println(XmlConfigReader1.getInstance().getDriverName());
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}</span>

读取结果如下:


和xml一致,成功读取!



评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值