xpath小练习

来源:互联网 发布:香港专业教育学院 知乎 编辑:程序博客网 时间:2024/05/16 19:48

Demo3.java

package cn.itcast;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;import java.io.File;import java.util.List;/** * Created by LiJing on 2017/9/2. */public class Demo3 {    public static void main(String[] args) throws DocumentException {        Document document = new SAXReader().read(new File("./personList.html"));        String xpath = "//tbody//tr";        List<Element> list =document.selectNodes(xpath);        for(Element element:list){            //获取到的是tr节点 然后获取子节点的文本 需要强转            System.out.print("编号:" + ((Element) element.elements().get(0)).getText());            System.out.print(" 姓名:" + ((Element) element.elements().get(1)).getText());            System.out.print(" 性别:"+((Element)element.elements().get(2)).getText());            System.out.print(" 年龄:" + ((Element) element.elements().get(3)).getText());            System.out.print(" 地址:" + ((Element) element.elements().get(4)).getText());            System.out.println(" 电话:"+((Element)element.elements().get(5)).getText());        }    }}

personList.html

<html>    <head>        <title>通讯录</title>        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />    </head>    <body>        <center><h1>通讯录</h1></center>        <table border="1" align="center" id="contactForm">            <thead>                 <tr><th>编号</th><th>姓名</th><th>性别</th><th>年龄</th><th>地址</th><th>电话</th></tr>            </thead>            <tbody>                <tr>                <td>001</td>                <td>张三</td>                <td></td>                <td>18</td>                <td>广州市天河区</td>                <td>134000000000</td>                </tr>                <tr>                <td>002</td>                <td>李四</td>                <td></td>                <td>20</td>                <td>广州市越秀区</td>                <td>13888888888</td>                </tr>                <tr>                <td>002</td>                <td>郭靖</td>                <td></td>                <td>30</td>                <td>广州市番禺区</td>                <td>1342214321</td>                </tr>            </tbody>        </table>    </body></html>

这里写图片描述