XML学习-Java学习记录

XML.png
使用xpath解析xml文档!!

import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

/**
 使用JUnit进行单元测试
 */
public class DemoXPath {

    private Document document;  //声明一个文档对象

    /**
     在每个测试方法前执行
     */
    @Before
    public void init() throws DocumentException {
        InputStream inputStream = DemoXPath.class.getResourceAsStream("/Contact.xml");
        document = new SAXReader().read(inputStream);
    }

    /**
     每个测试方法可以直接使用document对象
     绝对路径
     */
    @Test
    public void testAbsolutePath() {
        String xpath = "/contactList/contact/name";
        //得到第一个name元素,父元素转成子元素
        Element node = (Element) document.selectSingleNode(xpath);
        System.out.println(node.getText());
        //得到多个元素
        List<Node> nodes = document.selectNodes(xpath);
        for (Node node1 : nodes) {
            Element element = (Element) node1;
            System.out.println(element.getText());
        }
    }

    /**
     相对路径
     */
    @Test
    public void testRelativePath() {
        //得到contactList元素
        Node node = document.selectSingleNode("/contactList");
        //得到子元素,注:node也有这两个方法,  . 表示当前路径
        Element element = (Element) node.selectSingleNode("./contact/name");
        System.out.println(element.getText());
    }

    /**
     全文搜索
     */
    @Test
    public void testGlobalSearch() {
        List<Node> nodes = document.selectNodes("//email");
        for (Node node : nodes) {
            Element element = (Element) node;
            System.out.println(element.getText());
        }
    }

    /**
     属性查找
     */
    @Test
    public void testAttributeFind() {
        //得到的属性集合
        /*List<Node> nodes = document.selectNodes("//@id");
        for (Node node : nodes) {
            Attribute attribute = (Attribute) node;
            System.out.println("属性名:" + attribute.getName() + ",属性值:" + attribute.getValue());
        }*/

        //得到包含属性id的contact元素
        /*List<Node> nodeList = document.selectNodes("//contact[@id]");
        for (Node node : nodeList) {
            Element element = (Element) node;
            System.out.println(element);
        }*/

        //得到属性id=3的元素
        Node node = document.selectSingleNode("//contact[@id=3]");
        System.out.println(node);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值