由于要保存一些项目中只有一个而且很少改的,用数据库存储太浪费了,用xml保存吧。
1.现在来看下读xml,xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<company>
<tel>020-12345678-66</tel>
<tel>020-12345678-85</tel>
<introduce>
<![CDATA[
<br/><h1>公司简介</h1>
]]>
</introduce>
</company>
2.用dom4j 读,
package cn.rentbus;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
//import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4jXmlTest extends TestCase {
protected final Log logger = LogFactory.getLog(getClass());
private SAXReader reader;
private Document document;
private File xmlFile;
protected void setUp() throws Exception {
xmlFile = new File("WEB-INF/company.xml");
reader = new SAXReader();
document = reader.read(xmlFile);
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testReadXml() {
Element root = document.getRootElement();
for ( Iterator i = root.elementIterator( "tel" ); i.hasNext(); ) {
Element tel = (Element) i.next();
logger.info("tel: "+tel.getTextTrim());
// do something
}
logger.info("==== XPath use on tel ====");
List list = document.selectNodes("/company/tel" );
for(Element tel : (List<Element>) list) {
logger.info("tel: "+tel.getTextTrim());
}
for ( Iterator i = root.elementIterator( "introduce" ); i.hasNext(); ) {
Element introduce = (Element) i.next();
logger.info("introduce: "+introduce.getTextTrim());
// do something
}
logger.info("==== XPath use on introduce ====");
Node node = document.selectSingleNode("/company/introduce");
String introduce = node.getText();
logger.info("introduce: "+introduce.trim());
}
}
注意:如果用到XPath,需要jaxen-1.1-beta-6.jar(发本包/lib下有)
我的环境:
dom4j-1.6.1.jar
jaxen-1.1-beta-6.jar
posted on 2007-09-05 23:58
流浪汗 阅读(3635)
评论(2) 编辑 收藏 所属分类:
OpenSource