dom4j 学习

直接看代码..
dom4j 的一般使用都在里面了
/lib/dom4j-1.6.1.jar
/lib/jaxen-1.1-beta-6.jar
package  useDom4j.test.supper;

import  java.io.File;
import  java.io.FileOutputStream;
import  java.io.IOException;
import  java.io.InputStream;
import  java.io.OutputStream;
import  java.net.URL;
import  java.util.Iterator;
import  java.util.List;
import  java.util.regex.Matcher;
import  java.util.regex.Pattern;

import  javax.xml.parsers.DocumentBuilder;
import  javax.xml.parsers.DocumentBuilderFactory;

import  junit.framework.TestCase;

import  org.dom4j.Document;
import  org.dom4j.DocumentFactory;
import  org.dom4j.DocumentHelper;
import  org.dom4j.Element;
import  org.dom4j.Node;
import  org.dom4j.QName;
import  org.dom4j.Visitor;
import  org.dom4j.VisitorSupport;
import  org.dom4j.XPath;
import  org.dom4j.io.DOMReader;
import  org.dom4j.io.HTMLWriter;
import  org.dom4j.io.OutputFormat;
import  org.dom4j.io.SAXReader;
import  org.dom4j.io.XMLWriter;


public   class  useDom4jTest  extends  TestCase {

    
// use all
     private  String path ;
    
private  ClassLoader clo;
    
//  file path -> bin 
     private  String classPath ;
    
// use save 
     static   private  Document doc;
    
private  String filese;

    
protected   void  setUp()  throws  Exception {
        
super .setUp();
        path 
=   " useDom4j/test/config/test.xml " ;
        clo 
=   this .getClass().getClassLoader();
        classPath 
=  System.getProperty( " java.class.path " ).split( " ; " )[ 0 ]   ;
        filese 
=  System.getProperty( " file.separator " );
    }

    
protected   void  tearDown()  throws  Exception {
        
super .tearDown();
    }

    
    
public   void  testRead() throws  Exception{
        SAXReader sax 
=   new  SAXReader();
        
// File read
        Document docF  =   sax.read(
                
new  File(clo.getResource(path).getFile())
                    );
        assertNotNull(
" is File saxReader err " ,docF);
        
        
// InPutStream read 
        Document docI  =  sax.read( clo.getResourceAsStream(path) );
        assertNotNull(
" is InPutStream saxReader err " ,docI);
        
        
// URL read 
        Document docU  =  sax.read( clo.getResource(path) );
        assertNotNull(
" is Url saxReader err " ,docU);
        
    }
    
    
/**  converts a W3C DOM document into a dom4j document  */
    
public   void  testConversion()  throws  Exception{
          DocumentBuilderFactory domfac
= DocumentBuilderFactory.newInstance();
          DocumentBuilder dombuilder
= domfac.newDocumentBuilder();
          InputStream input 
=   clo.getResourceAsStream(path) ;
          org.w3c.dom.Document doc3c 
=  dombuilder.parse( input );
          DOMReader xmlReader 
=   new  DOMReader();
          assertEquals( 
"  Conversion : W3C DOM-> dom4j DOM err " ,
                  xmlReader.read(doc3c) 
instanceof  Document, true  );
      }
      
    
public   void  testCreate() throws  Exception{
          DocumentFactory factory 
=  DocumentFactory.getInstance();
          doc 
=  factory.createDocument();
        
// root Create
          Element root  =  doc.addElement( " testElement " );
          assertNotNull(
" is root Create err " ,root);
          
           Element author2 
=  root.addElement(  " author "  )
              .addAttribute( 
" name " " Toby "  )
              .addAttribute( 
" location " " Germany "  )
              .addText( 
" Tobias Rademacher "  );

            Element author1 
=  root.addElement(  " author "  )
              .addAttribute( 
" name " " James "  )
              .addAttribute( 
" location " " UK "  )
              .addText( 
" James Strachan "  );
            
            
// Test Create 
            
// use XPath ->jaxen-xxx.jar  
            assertEquals( " create Element author2 err " ,
                    doc.selectSingleNode(
" /testElement/author[@name='Toby'] " ).getText()
                    ,
" Tobias Rademacher " );
            assertEquals(
" create Element author1 err " ,
                    doc.selectSingleNode(
" /testElement/author[@location='UK']/@name " ).getText()
                    ,
" James " );
    }



     
public   void  testPrintingHTML() throws  Exception{
           String testSaveXml 
=   " useDom4j/test/config/testHtml.html " ;
           
           testSaveXml 
=  classPath + filese + testSaveXml;
          
           File file 
=  getFile(testSaveXml);
           
// Save file.html 
           HTMLWriter writer  =   new  HTMLWriter( new  FileOutputStream( file ));
           writer.write(
new  SAXReader().read( clo.getResource(path) ));
           writer.flush();
     }
    
    
public   void  testIterator(){
        Element root 
=   this .doc.getRootElement();
        
        
// Iterator
        Iterator elementIterator  =  root.elementIterator();
        
while (elementIterator.hasNext()){
          Element element 
=  (Element)elementIterator.next();
          assertNotNull(
" not attr name " , element.selectSingleNode( " ./@name " ) );
          assertNotNull(
" not attr location " , element.selectSingleNode( " ./@location " ) );
          assertNotNull(
" not Text  " , element.selectSingleNode( " . " ).getText() );
        }
        
        
// for -> ./XX
         for  (  int  i  =   0 , size  =  root.nodeCount(); i  <  size; i ++  ) {
            Node node 
=  root.node(i);
            
if  ( node  instanceof  Element ) {
              Element element 
=  (Element)node;
              assertNotNull(
" not attr name " , element.selectSingleNode( " ./@name " ) );
                assertNotNull(
" not attr location " , element.selectSingleNode( " ./@location " ) );
                assertNotNull(
" not Text  " , element.selectSingleNode( " . " ).getText() );
            }
        }
        
        
// List 
        List elements  =  root.elements();
        
int  size  =  elements.size() ;
        
if  ( size  >   4  ) {
          elements.subList( 
3 4  ).clear();
          assertEquals(
" List is not clear " ,size - elements.size() == 1 , true );
        }

    }
    
    
/**  use test.xml test
         xpath -> /project/organization/
         <organization>
             <name>MetaStuff Ltd.</name>
             <url>
http://sourceforge.net/projects/dom4j </url>
             <logo>
http://sourceforge.net/sflogo.php?group_id=16035 </logo>
          </organization> 
          
          xpath -> /project/dependencies/dependency[groupId='msv']
            <dependency>
              <groupId>msv</groupId>
              <artifactId>xsdlib</artifactId>
              <version>20030807</version>
              <url>
https://msv.dev.java.net/ </url>
            </dependency>
    
*/
    
public   void  testXpath() throws  Exception{
        XPath xpathSelector 
=  DocumentHelper.createXPath( " /project/organization/* " );
        Document docT 
=   new  SAXReader().read( clo.getResourceAsStream(path) );
        List results 
=  xpathSelector.selectNodes(docT);
        
for  ( Iterator iter  =  results.iterator(); iter.hasNext(); ) {
          Element element 
=  (Element) iter.next();
          
if (element.getName().equals( " name " )){
              assertEquals(
" name err " , element.getText().equals( " MetaStuff Ltd. " ), true );
          }
          
if (element.getName().equals( " url " )){
              assertEquals(
" url err " , element.getText().equals( " http://sourceforge.net/projects/dom4j " ), true );
          }
          
if (element.getName().equals( " logo " )){
              assertEquals(
" logo err " , element.getText().equals( " http://sourceforge.net/sflogo.php?group_id=16035 " ), true );
          }
        }
        
        
//  select 
        String url  =  docT.valueOf(  " /project/dependencies/dependency[groupId='msv']/url "  );
        assertEquals(
" Url err " , url.equals( " https://msv.dev.java.net/ " ), true );
        Number count 
=  docT.numberValueOf(  " /project/dependencies/dependency[groupId='msv']/version "  );
        assertEquals(
" Url err " , count.intValue() == 20030807 , true );
        
    }

    
    
public   void  testVisitor(){
        Visitor visitor 
=   new  VisitorSupport() {
            
public   void  visit(Element element) {
              System.out.println(
                
" Entity name:  "   +  element.getName()   +   "  text : "   +  element.getText()
              );
            }
          };

          doc.accept( visitor );
    }

    
//   element.clone ;  element.createCopy ;   
     public   void  testInsertElementAt()  throws  Exception{
        Element root 
=   this .doc.getRootElement();
        Element oldElement 
=  (Element)doc.selectSingleNode( " /testElement/author[@name='Toby'] " );
        Element newElement 
=  (Element) oldElement.clone();
        List list 
=  root.content();
        list.add( root.indexOf(oldElement)
+ 1 ,newElement );

     }
    
    
    
    
     
public   void  testSave() throws  Exception{
           String testSaveXml 
=   " useDom4j/test/config/testSave.xml " ;
           
           testSaveXml 
=  classPath + filese + testSaveXml;
          
           File file 
=  getFile(testSaveXml);
           
// Save file.xml 
           XMLWriter writer  =   new  XMLWriter( new  FileOutputStream( file ));
           writer.write(doc);
           writer.flush();
     }

     
     
    
private  File getFile(String testSaveXml)  throws  IOException {
        File file 
=   null  ;
           URL url 
=  clo.getResource(testSaveXml);
           
if (url == null ){
               file 
=   new  File(testSaveXml);
               file.createNewFile();
           }
else {
               file 
=   new  File(  url.getFile() );
           }
        
return  file;
    }
    
    
}

引用:http://freezingxu.blog.com.cn/archives/2006/1892647.shtml
/**
  * 对指定的节点增加属性和文本
  * 
@param  elmt
  * 
@param  name
  * 
@param  value
  * 
@param  text
  * 
@return
  
*/
 
public  Element addAttribute(Element elmt,String name,String value){
  elmt.addAttribute(name,value);
  
return  elmt;
 }
 
 
/**
  * 修改指定节点的属性和文本
  * 
@param  elmt
  * 
@param  name
  * 
@param  value
  * 
@param  text
  * 
@return
  
*/
 
public  Element setAttribute(Element elmt,String name,String value){
  Attribute attribute 
=  elmt.attribute(name);
  
// attribute.setName(name);
  attribute.setValue(value);
  List list 
=   new  ArrayList();
  list.add(attribute);
  elmt.setAttributes(list);
  
return  elmt;
 }
 
 
/**
  * 删除指定节点的指定属性
  * 
@param  elmt
  * 
@param  name
  * 
@return
  
*/
 
public  Element removeAttribute(Element elmt,String name){
  elmt.remove(elmt.attribute(name));
  
return  elmt;
 }
 
 
/**
  * 输出为文件
  * 
@param  doc
  * 
@throws  IOException
  
*/
 
public   void  writeFile(Document doc)  throws  IOException{
  FileWriter out 
=   new  FileWriter(  " d:/newQuery.xml "  );
  doc.write(out);
  out.flush();
  out.close();
 }

你可能感兴趣的:(dom4j 学习)