dom4j 学习

Posted on 2007-11-07 17:03 yukui 阅读(506) 评论(0)  编辑  收藏
zz G_G
直接看代码..
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( 
34 ).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;
    }
    
    
}

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


网站导航:
 

posts - 131, comments - 12, trackbacks - 0, articles - 32

Copyright © yukui