2007年5月13日星期日

dom4j(Version 1.6.1)快速入门

Parsing XML

或许你想要做的第一件事情就是解析一个某种类型的XML文档,用dom4j很容易做到。请看下面的示范代码:

import java.net.URL;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class Foo {

  public Document parse(URL url) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(url);
    return document;
  }
}

使用迭代器(Iterators)

我们可以通过多种方法来操作XML文档,这些方法返回java里标准的迭代器(Iterators)。例如:

public void bar(Document document) throws DocumentException {
  Element root = document.getRootElement();
  //迭代根元素下面的所有子元素
  for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
    Element element = (Element) i.next();
    //处理代码
  }

  //迭代根元素下面名称为"foo"的子元素
  for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {
    Element foo = (Element) i.next();
    //处理代码
  }

  // 迭代根元素的属性attributes)元素
  for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
    Attribute attribute = (Attribute) i.next();
    // do something
  }
}

强大的XPath导航

在dom4j中XPath可以表示出在XML树状结构中的Document或者任意的节点(Node)(例如:Attribute,Element 或者 ProcessingInstruction等)。它可以使在文档中复杂的操作仅通过一行代码就可以完成。例如:

public void bar(Document document) {
  List list = document.selectNodes( "//foo/bar" );

  Node node = document.selectSingleNode( "//foo/bar/author" );

  String name = node.valueOf( "@name" );
}

如果你想得到一个XHTML文档中的所有超文本链接(hypertext links)你可以使用下面的代码:

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();
  }
}

如果你需要关于XPath语言的任何帮助,我们强烈推荐这个站点Zvon tutorial他会通过一个一个的例子引导你学习。

快速遍历(Fast Looping)


如果你不得不遍历一个非常大的XML文档,然后才去执行,我们建议你使用快速遍历方法(fast looping method),它可以避免为每一个循环的节点创建一个迭代器对象,如下所示:

public void treeWalk(Document document) {
  treeWalk( document.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....
    }
  }
}

生成一个新的XML文档对象

在dom4j中你可能常常希望用程序生成一个XML文档对象,下面的程序为你进行了示范:

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Foo {

  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;
  }
}

将一个文档对象写入文件中

将一个文档对象写入Writer对象的一个简单快速的途径是通过write()方法。

FileWriter out = new FileWriter( "foo.xml" );
document.write( out );

如果你想改变输出文件的排版格式,比如你想要一个漂亮的格式或者是一个紧凑的格式,或者你想用Writer 对象或者OutputStream 对象来操作,那么你可以使用XMLWriter 类。

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Foo {

  public void write(Document document) throws IOException {

    // 写入文件
    XMLWriter writer = new XMLWriter(new FileWriter( "output.xml" ));
    writer.write( document );
    writer.close();


    // 以一种优雅的格式写入System.out对象
    OutputFormat format = OutputFormat.createPrettyPrint();
    writer = new XMLWriter( System.out, format );
    writer.write( document );

    // 以一种紧凑的格式写入System.out对象
    format = OutputFormat.createCompactFormat();
    writer = new XMLWriter( System.out, format );
    writer.write( document );
  }
}

转化为字符串,或者从字符串转化

如果你有一个文档(Document)对象或者任何一个节点(Node)对象的引用(reference),象属性(Attribute)或者元素(Element),你可以通过asXML()方法把它转化为一个默认的XML字符串:

Document document = ...;
String text = document.asXML();

如果你有一些XML内容的字符串表示,你可以通过DocumentHelper.parseText()方法将它重新转化为文档(Document)对象:

String text = " James ";
Document document = DocumentHelper.parseText(text);

通过XSLT样式化文档(Document)


使用Sun公司提供的JAXP API将XSLT 应用到文档(Document)上是很简单的。它允许你使用任何的XSLT引擎(例如:Xalan或SAXON等)来开发。下面是一个使用JAXP创建一个转化器(transformer),然后将它应用到文档(Document)上的例子:

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;

import org.dom4j.Document;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;

public class Foo {

  public Document styleDocument(Document document, String stylesheet)throws Exception {

    // 使用 JAXP 加载转化器
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer(new StreamSource( stylesheet ));

    // 现在来样式化一个文档(Document)
    DocumentSource source = new DocumentSource( document );
    DocumentResult result = new DocumentResult();
    transformer.transform( source, result );

    // 返回经过样式化的文档(Document)
    Document transformedDoc = result.getDocument();
    return transformedDoc;
  }
}



需要加入的包:
dom4j
saxpath
jaxen

package com.freezingxu.testDom4J;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class TestDom4J {
  /**
  * 获得XML文档
  * @param url
  * @return
  * @throws DocumentException
  * @throws FileNotFoundException
  */
  public Document parse(String url) throws DocumentException,FileNotFoundException{
    SAXReader saxReader = new SAXReader();
    File file = new File(url);
    InputStream in = new FileInputStream(file);
    Document doc = saxReader.read(in);
    return doc;
  }

  /**
   * 获得XML文件中的根节点
   * @param doc
   * @return
   */
  public Element getRootElement(Document doc){
    Element element = doc.getRootElement();
    System.out.println( "Root=" +element.getName());
    return element;
   }

  /**
  * 获得指定根节点下的所有节点
  * @param root
  */
  public Collection print(Element root){
    Collection coll = new ArrayList();
     Iterator itor = root.elementIterator();
     while(itor.hasNext()){
      Element e = (Element)itor.next();
      coll.add(e);
       System.out.println( "Element=" + e.getName());
    }

     return coll;
  }

   /**
  * 获得指定根节点下的指定节点
   * @param root
   * @param name
   * @return
   */
   public Collection getElement(Element root,String name){
    Collection coll = new ArrayList();
     Iterator itor = root.elementIterator(name);

     while(itor.hasNext()){
      Element e = (Element)itor.next();
       coll.add(e);
      System.out.println( "Element=" + e.getName());
     }
    return coll;
   }

  /**
   * 获得指定节点的所有属性
   * @param root
   */
  public void printAttribute(Element root){
     Iterator itor = root.attributeIterator();
     while(itor.hasNext()){
       Attribute attr = (Attribute)itor.next();
      String attributeName = attr.getName();
       String attributeValue = attr.getValue();
       System.out.println( "Name=" + attributeName + " and Value=" + attributeValue);
     }
  }

   /**
   * 使用xPath直接获得节点
  * @param doc
   * @param xPath
   * @return
   */
  public List getNodes(Document doc,String xPath){
     List list = doc.selectNodes(xPath);
     return list;
  }

   /**
  * 使用xPath获得指定节点的指定属性
   * @param node
   * @param xPath
   * @return
   */
  public String getNodeAttribute(Element node,String xPath){
     String attributeValue = node.valueOf(xPath); //获得属性的值
     String attributeText = node.getText(); //获得属性的文本
     return attributeValue;
  }

   /**
   * main
   * @param args
   * @throws FileNotFoundException
   * @throws DocumentException
  */
   public static void main(String []args) throws FileNotFoundException, DocumentException{
    TestDom4J t = new TestDom4J();
    Document doc = t.parse( "d:/query.xml" );
     Element rootElement = t.getRootElement(doc);
    t.print(rootElement);
    t.printAttribute(rootElement);
     Collection elmtColl = t.getElement(rootElement, "dwlx" );
    Iterator elmtItor = elmtColl.iterator();
     while(elmtItor.hasNext()){
      Element e = (Element)elmtItor.next();
       Collection coll = t.print(e);
       Iterator itor = coll.iterator();
      while(itor.hasNext()){
         Element e2 = (Element)itor.next();
         t.printAttribute(e2);
       }
     }

     //xPath
     List list = t.getNodes(doc, "//root/dwlx/value" );
    Iterator xPathItor = list.iterator();
    while(xPathItor.hasNext()){
       Element node = (Element)xPathItor.next();
       String s = t.getNodeAttribute(node, "@name" );
       System.out.println(s);
     }
   }
}

//////////附件:query.xml//////////



 
  all
  00
  68
 

 
   all
   0
   1
 

 
  all
  0
   1
  2
  3
  4
  5
  6
 

没有评论: