`
阅读更多
废话不说了,看了上篇Visitor访问者模式---------学习dom4j时遇到的顺便拿来交流 这个一看就懂了
package org.bulktree.xml;

import java.io.File;

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

/** *//**
 * dom4j访问者模式解析xml文档
 * 
@author bulktree Email: laoshulin@gmail.com
 * @date Aug 10, 2008
 
*/

public class ReadXmlVisitor {

    ReadXmlVisitor() 
{

        File file 
= new File("student.xml");
        SAXReader saxReader 
= new SAXReader();

        
try {
            Document doc 
= saxReader.read(file);
            doc.accept(
new MyVisitor());
        }
 catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    
    
public static void main(String[] args) {
        
new ReadXmlVisitor();
    }


}


/**//*
 * org.dom4j 包里有Visitor接口,VisitorSupport是它的实现类,定义了多个重载的visit方法
 
*/

class MyVisitor extends VisitorSupport {
    
public void visit(Attribute attr) {
        String name 
= attr.getName();
        String value 
= attr.getValue();

        System.out.println(
"Attribute--> " + name + " : " + value);
    }


    
public void visit(Element element) {
        String name 
= element.getName();
        
if (element.isTextOnly()) {
            System.out
                    .println(
"Element--> " + name + " : " + element.getText());
        }
 else {
            System.out.println(
"Element-->" + name);
        }

    }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics