/**
使用xpath技术取得xml文件中任意级别下的内容 基于dom4j的xpath技术
1)能够在xml文件中,快速定位需要元素,无需从根元素一个一个的导航到需要的子元素
Document.selectNodes():取得所有符合xpath格式的元素
Document.selectSingleNode():取得所有符合xpath格式的元素的第一个元素
Node类型是Element/Text/Attribute/Document/...类型的父接口
*/
import java.io.File;import java.util.List;import java.util.Scanner;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXContentHandler;import org.dom4j.io.SAXReader;import org.junit.Test;/** * 使用xpath技术取得xml文件中任意级别下的内容 基于dom4j的xpath技术 * 1)能够在xml文件中,快速定位需要元素,无需从根元素一个一个的导航到需要的子元素 * Document.selectNodes():取得所有符合xpath格式的元素 * Document.selectSingleNode():取得所有符合xpath格式的元素的第一个元素 * Node类型是Element/Text/Attribute/Document/...类型的父接口 * */public class Xpath { @Test public void xpathtest() throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read(new File("src/day2/domx/car.xml")); String xpath = "//单价"; List<Element> elementList = document.selectNodes(xpath); for (Element e : elementList) { System.out.println(e.getText()); System.out.println("================="); } } @Test public void xpathtest1() throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read(new File("src/day2/domx/car.xml")); String xpath = "//单价"; List<Element> elementList = document.selectNodes(xpath); System.out.println("第二辆汽车的单价是:" + elementList.get(1).getText()); } @Test public void xpathtest2() throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read(new File("src/day2/domx/car.xml")); String xpath = "//单价"; Element element = (Element) document.selectSingleNode(xpath); System.out.println("第一辆汽车的单价是:" + element.getText()); } @Test public void login() throws Exception { // 读取用户在键盘的输入信息 Scanner scanner = new Scanner(System.in); System.out.println("用户名:"); String username = scanner.nextLine(); System.out.print("密码:"); String password = scanner.nextLine(); // System.out.println(username+":"+password); //解析XML文件,并查询指定的元素 SAXReader saxReader = new SAXReader(); Document document = saxReader.read(new File("src/day2/domx/users.xml")); String xpath = "//user[@username='"+username+"' and @password='"+password+"']" ; Element element = (Element) document.selectSingleNode(xpath); if(element != null) { System.out.println("登陆成功"); }else { System.out.println("登陆失败"); } }}
user.xml
<?xml version="1.0" encoding="UTF-8"?><root> <user id = "id001" username ="liwen" password="123456"></user> <user id = "id002" username ="python" password="23456"></user></root>
结果:
用户名:
liwen
密码:123456
登陆成功