免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1116 | 回复: 0
打印 上一主题 下一主题

Dom4j的使用日志 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-03-25 17:00 |只看该作者 |倒序浏览
   今天首次使用了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
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP