XML文档:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students>
<student number="0001">
<name id="itcast">tom</name>
<age>18</age>
<sex>male</sex>
</student>
<student number="0002">
<name>jack</name>
<age>18</age>
<sex>female</sex>
</student>
</students>
解析代码块:
package jsoup;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* DOM4J
*/
public class DOM4J_Demo1 {
public static void main(String[] args) throws Exception {
//创建解析器
SAXReader reader = new SAXReader();
//解析xml文档
Document document = reader.read( "E:\\IdeaProject\\HTML\\day12_XML\\src\\xml\\student.xml" );
//获得根节点
Element root = document.getRootElement();
System.out.println(root.getName());
//查找根节点下的子节点 .element() .elements()
Element element = root.element("student");//第一个student
//获取子节点的标签内容
Element name = element.element( "name" );
Element age = element.element( "age" );
Element sex = element.element( "sex" );
System.out.println(name.getText());
System.out.println(age.getText());
System.out.println(sex.getText());
Object student = root.elements( "student" ).get( 1 );//第二个student
}
}
解析结果:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.dom4j.io.SAXContentHandler (file:/E:/IdeaProject/HTML/day12_XML/libs/dom4j-1.6.1.jar) to method com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser$LocatorProxy.getEncoding()
WARNING: Please consider reporting this to the maintainers of org.dom4j.io.SAXContentHandler
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
第一个student:
tom
18
male
Process finished with exit code 0