在dom4j中使用XPath的简单实例
如下所示:
package com.wzh.test.xpath; import java.io.File; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Node; import org.dom4j.io.SAXReader; public class Demo4 { 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); //检测xml文档是否有匹配的用户名和密码 String username="aaa"; String password="123"; reader=new SAXReader(); document=reader.read(new File("src/users.xml")); Node node=document.selectSingleNode("//user[@username='"+username+"'" + " and @password='"+password+"']"); if(node==null) { System.out.println("用户名密码错误"); } else { System.out.println("登录成功"); } } }
book.xml
<?xml version="1.0" encoding="utf-8"?> <书架> <书> <书名>Java就业培训教材</书名> <作者>张孝祥</作者> <售价>39.00元</售价> </书> <书> <书名>Java网页开发</书名> <作者>张孝祥</作者> <售价>29.00元</售价> </书> </书架>
users.xml
<?xml version="1.0" encoding="UTF-8"?> <users> <user id="1" username="aaa" password="123" email="[email protected]"></user> <user id="2" username="bbb" password="456" email="[email protected]"></user> </users>
相关推荐
realhero 2014-04-30
kenvie 2012-06-13
liaoxuewu 2020-04-10
ELEMENTS爱乐冬雨 2019-10-21
Yakamoz 2014-09-05
kenvie 2017-10-19
DodderB 2017-10-19
kenvie 2013-06-24
HiramYong 2013-04-14
Yakamoz 2014-09-05
hongyuancao 2011-11-14
katelynlily 2012-09-07
Yakamoz 2012-06-20
道 2012-06-13
abchywabc 2012-04-16
kenvie 2012-03-06