visitor.java
来自「孙鑫JAVA从入门到精通配套练习程序。所有程序都实际运行过」· Java 代码 · 共 50 行
JAVA
50 行
//访问类的使用(遍历文档树)
import java.io.File;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
public class Visitor
{
public static void main(String[] args)
{
SAXReader saxReader = new SAXReader();
try
{
Document doc = saxReader.read(new File("students.xml"));
//使用VisitA类对象中的方法遍历文档树
doc.accept(new VisitorA());
}
catch (DocumentException e)
{
e.printStackTrace();
}
}
private static class VisitorA extends VisitorSupport
{
//针对文档树中不同的结点类型执行不同的处理代码段
public void visit(Attribute node)
{
System.out.println("Attribute: " + node.getName() + "=" + node.getValue());
}
public void visit(Element node)
{
if (node.isTextOnly())
{
System.out.println("Element: " + node.getName() + "=" + node.getText());
}
else
{
System.out.println("--------" + node.getName() + "--------");
}
}
public void visit(ProcessingInstruction node)
{
System.out.println("PI:" + node.getTarget() + " " + node.getText());
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?