免费注册 查看新帖 |

Chinaunix

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

学习dom4j开源XML处理框架 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-11-30 23:11 |只看该作者 |倒序浏览

                                API帮助文档:http://www.dom4j.org/dom4j-1.6.1/apidocs/index.html
处理DEMO整理:
DEMO一:使用API生成XML文档
package xml.utils;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Document;
public class Foo {
    public Document createDocument() {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        Element author1 = root.addElement("author")
        .addAttribute("name","job")
        .addAttribute("location", "US")
        .addText("HKEBAO");
        return document;
    }
    public static void main(String[] args) {
        Document document = new Foo().createDocument();
        System.out.println(document.asXML());
    }
}
输出的结果:
HKEBAO
直接通过内置的API输出一段XML出来!
DEMO2 :通过使用API进行读取XML里面的数据。
原理:将XML解析到内存然后生成一棵DOCUMENT树!
解析的方法有多种
    /**
     * @param File
     * @return Document
     * @throws DocumentException
     * */
    public Document parse(File aFile) throws DocumentException {
        SAXReader xmlReader = new SAXReader();
        return xmlReader.read(aFile);
    }
注意:JAVA里面的File路径问题需要做一个专题讲一下!!!
public static void main(String[] args) throws MalformedURLException, DocumentException {
        File file = new File("dom4j.xml");      
        Document document = new Foo().parse(file);
        new Foo().bar(document);
        System.out.println(document.asXML());
    }
我们可以通过这样的方法来读出来一个XML文档。读出来了之后就可以方便进行解析了!
DEMO3
               
               
               
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/84280/showart_2107774.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP