MyJavaSite

我的Java学习研究日志
posts - 0, comments - 0, trackbacks - 0, articles - 1
  BlogJava ::  :: 新随笔 :: 联系 :: 聚合  :: 管理

DOM4J常用方法

Posted on 2005-10-24 18:57 MyWay 阅读(438) 评论(0)  编辑  收藏 所属分类: XML

 

dom4j是http://www.dom4j.org的一个开源的包
官方说明:
    dom4j is an easy to use, open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework and with full support for DOM, SAX and JAXP.
现在的版本是1.61
  DOM4J 最初,它是 JDOM 的一种智能分支。它合并了许多超出基本 XML 文档表示的功能,包括集成的 XPath 支持、XML Schema 支持以及用于大文档或流化文档的基于事件的处理。它还提供了构建文档表示的选项,它通过 DOM4J API 和标准 DOM 接口具有并行访问功能。
  为支持所有这些功能,DOM4J 使用接口和抽象基本类方法。DOM4J 大量使用了 API 中的 Collections 类,但是在许多情况下,它还提供一些替代方法以允许更好的性能或更直接的编码方法。直接好处是,虽然 DOM4J 付出了更复杂的 API 的代价,但是它提供了比 JDOM 大得多的灵活性。
  在添加灵活性、XPath 集成和对大文档处理的目标时,DOM4J 的目标与 JDOM 是一样的:针对 Java 开发者的易用性和直观操作。它还致力于成为比 JDOM 更完整的解决方案,实现在本质上处理所有 Java/XML 问题的目标。在完成该目标时,它比 JDOM 更少强调防止不正确的应用程序行为。
  DOM4J 是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件。如今你可以看到越来越多的 Java 软件都在使用 DOM4J 来读写 XML,特别值得一提的是连 Sun 的 JAXM 也在用 DOM4J。Hibernate也是用dom4j解析xml配置文件的。
常用的方法:
1.读取xml文件:

public static Document read(String filename) throws Exception
{
    org.dom4j.io.SAXReader saxreader
=new SAXReader();
    Document document
=saxreader.read(new File(filename));
return document;
}

2.保存xml

   XMLWriter xw = new XMLWriter(new BufferedWriter(new FileWriter(filePath)));
   xw.write(document);
   xw.close();

默认保存的文件为utf-8格式的如果想转为gb2312的则

    XMLWriter output = null;
    
/** 格式化输出,类型IE浏览一样 */
    OutputFormat format 
=             
     OutputFormat.createPrettyPrint();
    
/** 指定XML字符集编码 */
    format.setEncoding(
"gb2312");
    output 
= new XMLWriter(new FileWriter(new File(filename)),format);
    output.write(document);
    output.close(); 

3.读取xml文件内容:
取得Root节点:Element root=document.getRootElement();
遍历XML树:
如果xml文件为:

<?xml version="1.0" encoding="gb2312"?>
<root>
<infor>
<name>LC</name>
<age>21</age>
</infor>
<infor>
<name>YT</name>
<age>20</age>
</infor>
</root>

1) 枚举(Iterator)

Iterator iterate=root.elementIterator();
while(iterate.hasNext())
{
    Element ele
=(Element)iterate.next();
    Iterator ittt
=ele.elementIterator();
    
while(ittt.hasNext())
    
{
             Element eee
=(Element)ittt.next();    
               System.out.println(eee.getName()+eee.getText());  
          }

}

2)递归
递归也可以采用Iterator作为枚举手段,但文档中提供了另外的做法

public void treeWalk() 
{
    treeWalk(getRootElement());
}

public void treeWalk(Element element) 
{
   
for (int i = 0, size = element.nodeCount(); i < size; i++
   
{
     Node node 
= element.node(i);
     
if (node instanceof Element) 
     
{
         treeWalk((Element) node);
     }
 
    
else 
    

    
// do something.
    }

  }

}


3)Visitor模式
    只需要自定一个类实现Visitor接口即可

public class MyVisitor extends VisitorSupport 
{
   
public void visit(Element element)
   
{
       System.out.println(element.getName());
   }

   
public void visit(Attribute attr)
   
{
       System.out.println(attr.getName());
   }

}

只要调用root.accept(new MyVisitor())即可遍历
4)XPath方式:

List lt=document.selectNodes("//infor/name");
Iterator it
=lt.iterator();
while(it.hasNext())
{
     Element ele
=(Element)it.next();
     System.out.println(ele.getName()
+ele.getText());
}

4.建立xml。
1)通过字符串转XML
      Document document = DocumentHelper.parseText(text);
   通过document.asXML();可以打印出xml内容。
2)

public Document createDocument() 
{
Document document 
= DocumentHelper.createDocument();
Element root 
= document.addElement("root");
Element infor
= root.addElement("infor");
Element name 
= infor.addElement("name");
name.setText(
"lc");
Element age 
= infor.addElement("age");
age.setText(
"22");
return document;
}

5.增加节点。

public void addNode(String filePath)
{
    SAXReader saxReader 
= new SAXReader();
    
try
    
{
        Document doc 
= saxReader.read(new BufferedReader(new FileReader(filePath);  
        Element root 
= doc.getRootElement(); 
        
//取得根节点   
        Element infor = root.addElement("infor");
        Element name 
= infor.addElement("name");
        name.setText(
"tt");
        Element age 
= infor.addElement("age");
        age.setText(
"23");
        XMLWriter xw 
= new XMLWriter(new BufferedWriter(new FileWriter(filePath)));
    xw.write(doc);
    xw.close();
    }

    
catch(Exception e)
    
{
    }

}

6.修改节点很简单。。即在遍历的过程中查找节点进而进行修改。最后XMLWriter保存即可。。。


只有注册用户登录后才能发表评论。


网站导航: