DOM4J详解

Dom4j

概念:dom4j是一个Java的XML API,是jdon升级版,用来读写XML文件
 DOM4j是一个易用,开源的库,用于XML,Xpath,XSLT,
 它应用于Java平台,采用Java集合框架并完全支持DOM,SAX和JAXP
 
 DOM4j整合两种思想(SAX、DOM)
 使用SAX的思想读取XML
 使用DOM的思想,在内存中创建一颗对象关系树,可以参照之前学的DOM
 
 
 解析XML文档,读写XML文档主要依赖于org.dom4j.io包,其中提供两个类:
    1.DOMReader
    2.SAXReader
      这两个类的调用方式是一致的
      



public class ss {
//从文件读取XML,输入文件名,返回XML文档
    public Document read(String fileName)throws MalformedURLException,DocumentException{
        //创建SAX对象
        SAXReader reader=new SAXReader();
        Document document=reader.read(new File(fileName));
        return document;

    }
//其中reader的read方法时重载的,可以从InputStream,File,Url等多种不同的源来读取
    //得到document对象就代表了整个XML


    /*
    * 注意:如果读取的字符编码是按照XML文件头定义的编码来转换,
    * 如果出现乱码的问题,将各处的编码改成一致即可
    * */

    //获取root节点,读取后的第二步,得到Root节点
    /*
    * 注意:所有的XML分析都是从Root元素节点开始
    *
    *
    * */
public Element getRootElement(Document doc){
    return doc.getRootElement();
}

//遍历XML树
//DOM4j方式遍历节点
    //枚举(iterator)
    //枚举所有的子节点
    for(Iterator i=root.elementIterator();
    i.hasNext();
    ){
    Element element= (Element) i.next();
    //do something
    }
//通过名称获取节点
    for(Iterator i=root.elementIterator(foo);
    i.hasNext();
    ){
        Element foo= (Element) i.next();
        //do something
    }
//通过枚举的属性
    for(Iterator i=root.attributeIterator();
    i.hasNext();
    ){
        Attribute attribute= (Attribute) i.next();
//do something
    }

    //2.递归
    /*
    * 递归也可以采用Iterator作为枚举的手段,提供另外一种方式
    * */
    public void treeWalk(){
        treeWalk(getRootElement());
    }

    public void treeWalk(Element element){
        for(int i=0;i<element.nodeCount();i++){
            Node node=element.node(i);

            //判断元素是否包含
            if(node instanceof Element){
                treeWalk((Element) node);

            }else{
                //do   something
            }
        }
    }


//Visitor模式
   /* Dom4j对Visitor的支持,可以大大减少代码量,并且层次清楚
    是GOF设计模式中的一种,
    原理:
       两种类相互保有对方的引用,并且一种作为visitor去访问Visitor,只需要实现它的接口*/

}
public class ss extends VisitorSupport{


//Visitor模式
   /* Dom4j对Visitor的支持,可以大大减少代码量,并且层次清楚
    是GOF设计模式中的一种,
    原理:
       两种类相互保有对方的引用,并且一种作为visitor去访问Visitor,只需要实现它的接口*/

   public void visit(Element element){
System.out.println(element.getName());
   }
    public void visit(Attribute attribute ){
        System.out.println(attribute.getName());
    }
//调用:root.accept(new MyVisitor())
   /* Visitor接口提供多种重载,根据XML不同的对象,
    将采用不同的方式去访问,上面给出的是Element,Attribute 的简单实现

    注意:
   1. VisitorSupport是Dom4j提供的默认的适配器,
    Visitor接口的Default Adapter的模式,这个模式给出了各种visit(*)的空实现
  2.这个visitor是自动遍历所有的子节点。
  如果是root.accept(new MyVisitor()),将遍历子节点,
  第一次使用时,需要自己遍历,一般在递归中使用

    */
      
      
 /*
* Xpath支持:
*    如访问一个节点,可以直接使用xpath选择
* */

public void bar(Document document){

    List list=document.selectNodes(//foo/bar);
    Node node=document.selectSingleNode(//foo/bar/author);
String name=node.valueof(@name);

}
 
 例如,如果想查找Xhtml文档中所有的超链接,
 
 /*
* Xpath支持:
*    如访问一个节点,可以直接使用xpath选择
* */

public void findLinks(Document document)throws DocumentException{

    List list=document.selectNodes(//a/@href);
            //遍历集合
            for(Iterator iter=list.iterator();iter.hasNext();){

                Attribute attribute= (Attribute) iter.next();

                String url=attribute.getValue();
    }

/*
* 字符串与XML的转换
* XML转换成字符串
* */
Document document1=...;
String text=document.asXML();
//将字符串转换成吗xml

    String text1="<name>james</name>";
Document document2=DocumentHelper.parseText(text1);


}

//将XSL转换XML


    public Document styleDocument(Document document,String stylesheet)throws Exception{
    //加载transformer
        TransformerFactory transformer=TransformerFactory.newInstance();

    Transformer transformer1=transformer.newTransformer(new StreamSource(stylesheet));
        DocumentSource documentSource=new DocumentSource(document);
        DocumentResult result=new DocumentResult();

        Document transformeDoc=result.getDocument();
    return transformeDoc;

    }

}

//创建XML:一般创建XML实在写文件之前,和StringBuffer一样



    public Document createDocument()throws Exception{
        Document document=DocumentHelper.createDocument();
        Element root=document.addElement("root");
        Element author=root.addElement("author").addAttribute(
                "name","james").addAttribute("location","UK");

return document;

//文件的输出:将一个Document或者Node通过write方法输出
        FileWriter out=new FileWriter("foo.xml");
        document.write(out);


    }

//如果你想要改变输出的格式,比如美化输出或者缩减格式,可以使用XMLWrite类实现
    public void write(Document document)throws IOException{
//指定文件
        XMLWriter writer=new XMLWriter(new FileWriter("abc.xml"));
writer.write(document);
writer.close();
//美化格式
        OutputFormat format=OutputFormat.createPrettyPrint();
        writer=new XMLWriter(System.out,format);
        writer.write(document);


  //缩减格式
      format=OutputFormat.createCompactFormat();
      writer=new XMLWriter(System.out,format);
      writer.write(document);

    }


使用Dom4j如何避免乱码?
写入的编码格式和读取的编码格式一致

 1.如何控制写入的编码
    
 XMLWriter writer1=new XMLWriter(
                      new PrintWriter("src/abc/bdc.xml","utf-8"),format);
 2.如何控制读取编码的格式
  <?xml version="1.0" encoding="GBK"?>
  其中encoding决定读取编码的格式,
  
  注意:encoding属性是由format.setEncoding("GBK")控制






  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值