XML解析器(二)DOM4J

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值