日常小结-XPath用于解析XML文档

前端之家收集整理的这篇文章主要介绍了日常小结-XPath用于解析XML文档前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用XPath的时候,除了dom4j以外,还需要额外添加一个.jar包-jaxen包。

package sax;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class Demo2 {

    //用XPath提取数据
    public static void main(String[] args) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/book.xml"));

        String value = document.selectSingleNode("//作者").getText();
        System.out.println(value);
    }
}

密码验证实例:

package sax;

import java.io.File;

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

public class Demo3 {

    public static void main(String[] args) throws DocumentException {
        String username = "aaa";
        String passwrod = "123";
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/users.xml"));

        Node node = document.selectSingleNode("//user[@username='"+username+"' and @password='"+passwrod+"']");

        if(node==null){
            System.out.println("用户名密码错误");
        }else{
            System.out.println("登录成功");
        }
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user id="1" username="aaa" password="123" email="aa@sina.com"/>
    <user id="2" username="bbb" password="123" email="aa@sina.com"/>
</users>

猜你在找的XML相关文章