07_XPath_01_入门

【工程截图】

 

【person.xml】

<?xml version="1.0" encoding="UTF-8"?>
<students>
    <student id="88888" phone="15888888888" sex="男">
        <name>张三</name>
        <name>张三2</name>
        <age>18</age>
        <school>清华</school>
    </student>
    <student id="99999" phone="15999999999" sex="女">
        <name>李四</name>
        <name>李四2</name>
        <age>28</age>
        <school>北大</school>
    </student>
    <student phone="15666666666" sex="男">啦啦啦</student>
    <AAAA>
        <student id="AAA">AAA哈哈哈</student>  <!-- student干扰项 -->
        <aa1>aa111</aa1>
        <aa2>aa222</aa2>
    </AAAA>
    <BBBB>
        <student id="BBB" sex="女">BBB哈哈哈</student> <!-- student干扰项 -->
    </BBBB>
</students>

 

【获取person.xml的Document对象,然后采集所需的数据,入门】

package com.Higgin.XPath;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class Demo01 {
    
    public static void main(String[] args)throws DocumentException,IOException {
        //获取对应的Document对象
        Document doc=new SAXReader().read(new File("./src/person.xml"));
        
        /**需求1:获取id属性值为88888的学生标签的sex属性
         * 已知:<student id="88888" phone="15888888888" sex="男">
         **/
        Element stuElem=(Element) doc.selectSingleNode("//student[@id='88888']");
        Attribute sexAttr=stuElem.attribute("sex");  //获取对应的Attribute属性对象
        System.out.println(sexAttr.getText());    //打印属性对象的属性值
        
        /**
         * 需求2:打印多个满足要求的标签的文本
         */
        List<Node> nameList= doc.selectNodes("//student/name[2]");
        for(Node node:nameList){
            System.out.println(node.getText());
        }
    }
}

【运行结果】

 

posted @ 2016-09-22 20:02  HigginCui  阅读(280)  评论(0编辑  收藏  举报