正在回答
3回答
那同学可以试试如下的代码,使用and连接两个位置条件进行查询,祝学习愉快~
1 | testor.xpath( "//employee[position()>=2 and position()<=7]" ); |
chrismorgen
2018-09-06 19:00:53
同学你好,在老师的课程中有讲到,如下代码就可以完成你说的需求。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | package com.imooc.dom4j; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; public class XPathTestor { public void xpath(String xpathExp){ String file = "src/hr.xml" ; SAXReader reader = new SAXReader(); try { Document document = reader.read(file); List<Node> nodes = document.selectNodes(xpathExp); for (Node node : nodes){ Element emp = (Element)node; System.out.println(emp.attributeValue( "no" )); System.out.println(emp.elementText( "name" )); System.out.println(emp.elementText( "age" )); System.out.println(emp.elementText( "salary" )); System.out.println( "==============================" ); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { XPathTestor testor = new XPathTestor(); // testor.xpath("/hr/employee"); // testor.xpath("//employee"); // testor.xpath("//employee[salary<4000]"); // testor.xpath("//employee[name='李铁柱']"); // testor.xpath("//employee[@no=3304]"); // testor.xpath("//employee[1]"); // testor.xpath("//employee[last()]"); //testor.xpath("//employee[position()<3]"); testor.xpath( "//employee[2] | //employee[7]" ); } } |
以下是显示结果,读取到2到7位置的数据。祝学习愉快~
chrismorgen
2018-09-06 16:10:56
你好!你所说的中间一段位置指的是什么呢?某个标签,还是标签中的属性呢?如果是写XPath表达式,要知道具体的位置。
xml的主要作用是作为配置文件,传输和存储数据的,所以,整体读取xml内容,或指定的某个标签的内容是比较常见的使用场景。如果比较精确的查找某个内容,更适合使用数据库。祝学习愉快!
从网页搭建入门Java Web2018版
- 参与学习 人
- 提交作业 1088 份
- 解答问题 10204 个
如果你有Java语言基础,又想以后从事Java Web开发,那么本路径是你的不二选择!本路径从网页搭建开始入手,通过大量案例来学习Java Web基础。定能助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧