- 论坛徽章:
- 0
|
今天首次使用了dom4j,感觉很方便,dom4j是一种开源框架,非常易于使用,可以在java平台上很好的处理XML, XPath and XSLT ,并且支持JAXP,DOM和SAX。其下载地址是:
http://jaist.dl.sourceforge.net/sourceforge/dom4j/dom4j-1.6.1.zip
,解压缩后主要使用其中的dom4j-1.6.1.jar和jaxen-1.1-beta-6.jar。
下面简要介绍下其用法:
1. 读取xml文件,生成Document对象,主要使用了SAXReader类:
//从文件读取XML,输入文件名,返回XML文档
public void read(String fileName) throws MalformedURLException, DocumentException {
SAXReader reader = new SAXReader();
document = reader.read(new File(fileName));
}
2. 获取根节点,使用document的getRootElement方法:
//获取根节点
public Element getRootElement(Document doc){
return doc.getRootElement();
}
3. 访问某个节点:
List listPathAttribute = document.selectNodes("/nancy-config/page/@path" ); //获取所有page的path属性
List listPageElement = document.selectNodes("/nancy-config/page" );//获取所有的page
Iterator iteratorListPathAttribute = listPathAttribute.iterator();
Iterator iteratorPageElement = listPageElement.iterator();
4. 创建新文档:
public Document createDocument() {
Document document = DocumentHelper.createDocument();
Element root = document.addElement( "root" );
Element author1 = root.addElement( "author" )
.addAttribute( "name", "James" )
.addAttribute( "location", "UK" )
.addText( "James Strachan" );
Element author2 = root.addElement( "author" )
.addAttribute( "name", "Bob" )
.addAttribute( "location", "US" )
.addText( "Bob McWhirter" );
return document;
}
5. 将Document写入文件中,也可以写入其它输出流中:
FileWriter out = new FileWriter( "foo.xml" );
document.write( out );
6. 与字符串互相转换:
//将document中的xml内容转换成字符串
String text = document.asXML();
//将字符串转换成document
String text = " James ";
Document document = DocumentHelper.parseText(text);
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/20181/showart_1879182.html |
|