dom4j的使用案例

 

package org.sun.dom4j.test;

 

import java.io.File;

 

import org.dom4j.Document;

import org.dom4j.Element;

import org.dom4j.Node;

import org.dom4j.io.SAXReader;

 

public class ParseXML {

    StringBuffer result=new StringBuffer();

    Document doc=null;

    public ParseXML(){}

   

    public void read(String fileName)throws Exception

    {

       SAXReader reader=new SAXReader();

       doc=reader.read(new File(fileName));

    }

   

    public void treeWalk(){

       treeWalk(doc.getRootElement());

    }

   

    public void treeWalk(Element element){

       for(int i=0,size=doc.nodeCount();i<size;i++){

           Node node=element.node(i);

           if(node instanceof Element){

               if(node.getName().trim().length()>0)result.append(node.getName()+" = ");

              else result.append("联系人记录");

              treeWalk((Element)node);

           }else{

               if(node.getText().trim().length()>0)result.append(node.getText()+"<br>");

           }

       }

    }

   

    public String toString(){

       return result.toString();

    }

}

你可能感兴趣的:(sun)