XPath 使用路径表达式在 XML 文档中进行导航
XPath 包含一个标准函数库
XPath 是 XSLT 中的主要元素
XPath 是一个 W3C 标准
第一步:导入xpath的支持包
第二步:使用xpath
1:定义xpath = "//name"
2:查询 dom.selectNodes(xpath);
public class Demo03_Xpath { @Test public void test1() throws Exception { SAXReader sax = new SAXReader(); Document dom = sax.read("./files/users.xml"); String xpath = "//name"; List<Element> list = dom.selectNodes(xpath); for(Element e:list){ System.err.println(e.getText()); } } }
用xpath实现登录:
@Test public void test2() throws Exception { SAXReader sax = new SAXReader(); Document dom = sax.read("./files/users.xml"); String xpath = "//user[name='张三'][pwd='22225666']"; Element e = (Element) dom.selectSingleNode(xpath); System.err.println(e); }
模糊查询:
@Test public void test3() throws Exception { SAXReader sax = new SAXReader(); Document dom = sax.read("./files/users.xml"); String xpath = "//user[contains(name,'赵')][contains(age,'3')]"; List<Element> list = dom.selectNodes(xpath); for(Element e:list){ System.err.println(e.asXML()); System.err.println("-----------------------"); } }
根据id查询:
@Test public void test4() throws Exception { SAXReader sax = new SAXReader(); Document dom = sax.read("./files/users.xml"); String xpath = "//user[@id='U001']"; Element e = (Element) dom.selectSingleNode(xpath); System.err.println(e.asXML()); }