1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package com.yitong.dom4j;
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* dom4j解析xml
* @author tingiting123
*
*/
public class TestDom4j {
public static void main(String[] args) throws Exception {
SAXReader reader = new SAXReader(); //获取解析器
Document document = reader.read( new File( "student.xml" )); //获取解析的文档对象
Element students = document.getRootElement(); //获取根节点
@SuppressWarnings ( "unchecked" )
List<Element> childElements = students.elements(); //获取根节点下的所有子节点
for (Element book : childElements) {
System.out.println( "id: " + book.attributeValue( "id" ));
// 方式一,未知子元素名情况下
@SuppressWarnings ( "unchecked" )
List<Element> elementList = book.elements(); //获取book节点下的所有子节点
for (Element ele :elementList) {
System.out.print(ele.getName() + ": " + ele.getText()+ "\t" );
}
System.out.println();
//方式二,已知子元素名的情况下
// System.out.println("name: " + book.elementText("name")+" \tage: " + book.elementText("age"));
}
}
}
-----------------------------------------------------------------------
student.xml
<?xml version="1.0" encoding="UTF-8"?>
----------------------------------------------------------
运行结果:
id: 1
|
XML解析之Dom4j解析
最新推荐文章于 2022-05-14 09:11:13 发布