解析xml的四种方式

1.DOM解析,官方的解析方式

2.SAX解析,民间的解析方式,基于事件解析

3.JDOM解析,第三方解析方式,比DOM解析快

4.DOM4J解析,性能最好,是JDOM的升级版

DOM4J解析案列:

1.先引入dom4j的jar包

2.读取xml文件信息

public class TestXml {
public static void main(String[] args) throws Exception {
// [1] 创建SAXReader对象, 用于读取xml文件
SAXReader reader = new SAXReader();
// [2] 读取xml文件, 得到Document对象
Document doc = reader.read(new File("src/scores2.xml"));
// [3] 获取根元素
Element root = doc.getRootElement();
// [4] 获取根元素下所有子元素
Iterator<?> it = root.elementIterator();
while(it.hasNext()) {
// 取出元素
Element e = (Element) it.next();
System.out.println(e.getName());
// 获取id属性
Attribute id = e.attribute("id");
System.out.println(id.getName() + "=" + id.getValue());
// 获取student的子元素
Element name = e.element("name");
Element course = e.element("course");
Element score = e.element("score");
// 打印
System.out.println(name.getName()+ "=" + name.getStringValue());
System.out.println(course.getName() + "=" + course.getText());
System.out.println(score.getName() + "=" + score.getText());
System.out.println("--------------------------------------");
}
}
}
 

猜你喜欢

转载自blog.csdn.net/qq_31580305/article/details/83184718