package cn.itcast.xml.xpath;
import java.io.File;
import java.util.Scanner;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
//使用Xpath,模拟用户登录
public class Demo2 {
public static void main(String[] args) throws Exception {
//读取用户在键盘的输入信息
Scanner scanner = new Scanner(System.in);
System.out.print("用户名:");
String username = scanner.nextLine();
System.out.print("密码:");
String password = scanner.nextLine();
//解析XML文件,并查询指定的元素
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new File("src/cn/itcast/xml/xpath/users.xml"));
自定义一个xpath
String xpath = "//user[@username='"+username+"' and @password='"+password+"']";
Element element = (Element) document.selectSingleNode(xpath);
如果用户输入的username,password 与xml中的相同
//输出结果if(element!=null){System.out.println("登录成功");}else{System.out.println("登录失败");}}}
//xml文件
<?xml version="1.0" encoding="UTF-8"?>
<root>
<user id="u01" username="jack" password="123456"/>
<user id="u02" username="marry" password="654321"/>
</root>