Dom4j 의 사용 (완전 하고 좋 은 글) –

 DOM4J dom4j.org       XML   ,         : 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. Dom4j      、    ,  XML,XPath XSLT。    Java  ,   Java         DOM,SAX JAXP。 DOM4J        。        XML-DOM  ,    。               (html),       。         。                 ,            ,       , ……           。    IBM developer     (    ),    XML        ,  DOM4J       ,          。(   DOM4J              )            DOM4J  XML    。           JDOM     ,      , DOM4J             ,        JDOM       。       ,”      ”。    DOM4J       。       JDOM,       ,              ,            ,    DOM4J 。         org.dom4j      :

Attribute Attribute   XML    
Branch Branch            XML  (Element)   (Docuemnts)          , 
CDATA CDATA    XML CDATA    
CharacterData CharacterData       ,         。 CDATA,Comment, Text. 
Comment Comment    XML      
Document    XML   
DocumentType DocumentType   XML DOCTYPE   
Element Element  XML    
ElementHandler ElementHandler    Element        
ElementPath   ElementHandler   ,                  
Entity Entity   XML entity 
Node Node    dom4j XML          
NodeFilter NodeFilter     dom4j                (predicate) 
ProcessingInstruction ProcessingInstruction    XML     . 
Text Text   XML     . 
Visitor Visitor     Visitor  . 
XPath XPath               XPath     

                。        ,              :

interface java.lang.Cloneable 
interface org.dom4j.Node 
  
  
interface org.dom4j.Attribute 
interface org.dom4j.Branch 
  
  
  
interface org.dom4j.Document 
interface org.dom4j.Element 
interface org.dom4j.CharacterData 
interface org.dom4j.CDATA 
interface org.dom4j.Comment 
interface org.dom4j.Text 
interface org.dom4j.DocumentType 
interface org.dom4j.Entity 
interface org.dom4j.ProcessingInstruction 
    ,        。      Node    。      ,          ClassCastException 。        (    DOM4J     ),         。1.                   XML  :  XML       org.dom4j.io ,    DOMReader SAXReader      ,         。          。

      //      XML,     ,  XML       public Document read(String fileName) throws MalformedURLException, DocumentException {        SAXReader reader = new SAXReader();        Document document = reader.read(new File(fileName));        return document;     }   

  ,reader read      ,   InputStream, File, Url          。   Document        XML。         ,          XML           。        ,                 。2.      Root         ,    Root  。  XML     ,  XML     Root     。

     public Element getRootElement(Document doc){        return doc.getRootElement();     }   

3.      XML  DOM4J    3        : 1)   (Iterator)

      //             for ( Iterator i = root.elementIterator(); i.hasNext(); ) {        Element element = (Element) i.next();        // do something     }     //      foo        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, size = element.nodeCount(); i < size; i++)     {            Node node = element.node(i);            if (node instanceof Element) {               treeWalk((Element) node);            } else { // do something….            }        } }   

3) Visitor         DOM4J Visitor   ,           ,      。           ,Visitor GOF      。                   ,      Visitor     Visitable。    DOM4J  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()) 

    Visitor      Visit()   ,  XML     ,           。      Element Attribute     ,            。VisitorSupport DOM4J        ,Visitor   Default Adapter  ,         visit(*)    ,      。       ,  Visitor           。   root.accept(MyVisitor),      。        ,         ,       Visitor,      。 4. XPath       DOM4J 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         ,         :

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

5.     XML                 XML   ,

      // XML       Document document = …;     String text = document.asXML(); //     XML     String text = <person> <name>James</name> </person>;     Document document = DocumentHelper.parseText(text);   

6  XSLT  XML

     public Document styleDocument(        Document document,        String stylesheet     ) throws Exception {     // load the transformer using JAXP     TransformerFactory factory = TransformerFactory.newInstance();     Transformer transformer = factory.newTransformer(        new StreamSource( stylesheet )     );     // now lets style the given document     DocumentSource source = new DocumentSource( document );     DocumentResult result = new DocumentResult();     transformer.transform( source, result );     // return the transformed document     Document transformedDoc = result.getDocument();     return transformedDoc; }   

7.   XML       XML        ,   StringBuffer    。

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

8.                       Document    Node  write    

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

             ,           ,   XMLWriter 

      public void write(Document document) throws IOException {        //             XMLWriter writer = new XMLWriter(            new FileWriter( output.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    ,  ,             , ElementHandler 。      ,      DOM4J. DOM4J    :(     ) http://www.dom4j.org/ DOM4J  (SourceForge),     1.4 http://sourceforge.net/projects/dom4j  Dom4j  XML          2004 9 27  20:21         dom4j  XML     ,    XML  ,  、  、    ,     (  )       。   dom4j     。    :http://jalorsoft.com/holen/   :  ([email protected])  :2004-09-11           dom4j  XML     ,    XML  ,  、  、    ,     (  )       。   dom4j     。   1.         dom4j sourceforge.net        ,     XML   。 2001 7        ,         ,       1.5。 dom4j    Java  ,        、  , Java ,dom4j     。      http://sourceforge.net/projects/dom4j      。   dom4j1.5      13M,     dom4j-1.5.zip    ,      dom4j-1.5.jar  ,             ,      jaxen-1.1-beta-4.jar  ,       ,        java.lang.NoClassDefFoundError: org/jaxen/JaxenException  ,          。   2.   XML  (holen.xml)         ,    XML  ,             。  

holen.xml 
<?xml version=”1.0″ encoding=”UTF-8″?> <books>     <!–This is a test for dom4j, holen, 2004.9.11–>     <book show=”yes”>        <title>Dom4j Tutorials</title>     </book>     <book show=”yes”>        <title>Lucene Studing</title>     </book>     <book show=”no”>        <title>Lucene in Action</title>     </book>     <owner>O’Reilly</owner> </books> 

          XML  ,         ,    ,        ,     [title],       [show],              [owner]  。   3.     XML    

  
    /**      *     XML  ,                * @param filename              * @return       , 0   , 1         */     public int createXMLFile(String filename){        /**       , 0   , 1    */        int returnValue = 0;        /**   document   */        Document document = DocumentHelper.createDocument();        /**   XML    books */        Element booksElement = document.addElement(”books”);        /**        */        booksElement.addComment(”This is a test for dom4j, holen, 2004.9.11″);        /**      book   */        Element bookElement = booksElement.addElement(”book”);        /**   show     */        bookElement.addAttribute(”show”,”yes”);        /**   title   */        Element titleElement = bookElement.addElement(”title”);        /**  title     */        titleElement.setText(”Dom4j Tutorials”);               /**         book */        bookElement = booksElement.addElement(”book”);        bookElement.addAttribute(”show”,”yes”);        titleElement = bookElement.addElement(”title”);        titleElement.setText(”Lucene Studing”);        bookElement = booksElement.addElement(”book”);        bookElement.addAttribute(”show”,”no”);        titleElement = bookElement.addElement(”title”);        titleElement.setText(”Lucene in Action”);               /**   owner   */        Element ownerElement = booksElement.addElement(”owner”);        ownerElement.setText(”O’Reilly”);               try{            /**  document          */            XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)));            writer.write(document);            writer.close();            /**     ,   1 */            returnValue = 1;        }catch(Exception ex){            ex.printStackTrace();        }                      return returnValue;     } 

    : Document document = DocumentHelper.createDocument();         XML    。   Element booksElement = document.addElement(”books”);         XML  ,         。 Element        : l         addComment:     l         addAttribute:     l         addElement:            XMLWriter      ,     XML         ,    OutputFormat  createCompactFormat()   createPrettyPrint()       ,    createCompactFormat()  ,      ,          。       holen.xml      :  

  
<?xml version=”1.0″ encoding=”UTF-8″?> <books><!–This is a test for dom4j, holen, 2004.9.11–><book show=”yes”><title>Dom4j Tutorials</title></book><book show=”yes”><title>Lucene Studing</title></book><book show=”no”><title>Lucene in Action</title></book><owner>O’Reilly</owner></books> 

  4.   XML            ,   : l           book   show      yes,    no l          owner     Tshinghua,   date   l          title   Dom4j Tutorials,        

  
    /**      *   XML     ,               *     dom4j       ,    ,          * @param filename             * @param newfilename                * @return       , 0   , 1         */     public int ModiXMLFile(String filename,String newfilename){        int returnValue = 0;        try{            SAXReader saxReader = new SAXReader();            Document document = saxReader.read(new File(filename));            /**       :   book   show      yes,    no */            /**   xpath     */            List list = document.selectNodes(”/books/book/@show” );            Iterator iter = list.iterator();            while(iter.hasNext()){               Attribute attribute = (Attribute)iter.next();               if(attribute.getValue().equals(”yes”)){                   attribute.setValue(”no”);               }              }                       /**             *       :  owner     Tshinghua             *   owner     date  ,date      2004-09-11,  date        type             */            list = document.selectNodes(”/books/owner” );            iter = list.iterator();            if(iter.hasNext()){               Element ownerElement = (Element)iter.next();               ownerElement.setText(”Tshinghua”);               Element dateElement = ownerElement.addElement(”date”);               dateElement.setText(”2004-09-11″);               dateElement.addAttribute(”type”,”Gregorian calendar”);            }                       /**       :  title   Dom4j Tutorials,       */            list = document.selectNodes(”/books/book”);            iter = list.iterator();            while(iter.hasNext()){               Element bookElement = (Element)iter.next();               Iterator iterator = bookElement.elementIterator(”title”);               while(iterator.hasNext()){                   Element titleElement=(Element)iterator.next();                   if(titleElement.getText().equals(”Dom4j Tutorials”)){                      bookElement.remove(titleElement);                   }               }            }                                try{               /**  document          */               XMLWriter writer = new XMLWriter(new FileWriter(new File(newfilename)));               writer.write(document);               writer.close();               /**     ,   1 */               returnValue = 1;            }catch(Exception ex){               ex.printStackTrace();            }                   }catch(Exception ex){            ex.printStackTrace();        }        return returnValue;     }     

    : List list = document.selectNodes(”/books/book/@show” ); list = document.selectNodes(”/books/book”);       xpath       。     setValue()、setText()      。     remove()       。   5.                          ,     UTF-8,          ,        ,                  ,     OutputFormat 。  

  
        /**      *    XML  ,             * @param filename      * @return      */     public int formatXMLFile(String filename){        int returnValue = 0;        try{            SAXReader saxReader = new SAXReader();            Document document = saxReader.read(new File(filename));            XMLWriter writer = null;            /**      ,  IE     */            OutputFormat format = OutputFormat.createPrettyPrint();            /**   XML   */            format.setEncoding(”GBK”);            writer= new XMLWriter(new FileWriter(new File(filename)),format);            writer.write(document);            writer.close();                 /**     ,   1 */            returnValue = 1;            }catch(Exception ex){            ex.printStackTrace();        }        return returnValue;     } 

    :   OutputFormat format = OutputFormat.createPrettyPrint();                ,     。   format.setEncoding(”GBK”);      GBK。   XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)),format);           ,     OutputFormat  ,           。   6.                      ,         。  

Dom4jDemo.java 
package com.holen.dom4j;   import java.io.File; import java.io.FileWriter; import java.util.Iterator; import java.util.List;   import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter;   /**  * @author Holen Chen 

좋은 웹페이지 즐겨찾기