解析xml文件

2种方式解析xml文件

1 递归的方式

public static void readNode(Element root, String prefix) {
if (root == null)
return;
// 获取节点的属性
List attrs = root.attributes();
if (attrs != null && attrs.size() > 0) {
System.err.print(prefix);
for (Attribute attr : attrs) {
System.err.print(attr.getValue() + ” “);
}
System.err.println();
}
// 获取他的子节点
List childNodes = root.elements();
prefix += “\t”;
for (Element e : childNodes) {
readNode(e, prefix);
}
}

2 通过辅助类的形式

public static void read2() {
try {
SAXReader reader = new SAXReader();
InputStream in = TestDom4j.class.getClassLoader().getResourceAsStream(“text.xml”);
Document doc = reader.read(in);
doc.accept(td.new MyVistor());
} catch (DocumentException e) {
e.printStackTrace();
}
}

class MyVistor extends VisitorSupport {
public void visit(Attribute node) {
System.out.println(“Attibute: ” + 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());
}
}
@Override
public void visit(ProcessingInstruction node) {
System.out.println(“PI:” + node.getTarget() + ” ” + node.getText());
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值