这句程序取到的是根节点下的第一个节点吗?如果要取department节点下的dname要怎么办?

来源:3-8 XPath实验室

慕娘0924178

2019-07-23 17:03:25

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="e:/java/eclipse-workspace/xml/src/hr-schema.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) {
		// TODO Auto-generated method stub
		XPathTestor xpt=new XPathTestor();
//		xpt.xpath("/hr/employee");
//		xpt.xpath("//employee");
//		xpt.xpath("//employee[salary<5000]");
//		xpt.xpath("//employee[name='李铁柱']");
//		xpt.xpath("//employee[@no=6302]");
//		xpt.xpath("//employee[1]");
//		xpt.xpath("//employee[last()]");
//		xpt.xpath("//employee[position()<3]");
		xpt.xpath("//employee[1]|//employee[3]");
		
	}

}
<?xml version="1.0" encoding="UTF-8"?>
<!-- 人力资源管理系统 -->
<hr xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="hr.xsd">
	<employee no="3310">
		<name>张三</name>
		<age>31</age>
		<salary>4000</salary>
		<departement>
			<dname>会计部</dname>
			<address>XX大厦-B803</address>
		</departement>
	</employee>
	<employee no="4502">
		<name>李四</name>
		<age>23</age>
		<salary>8000</salary>
		<departement>
			<dname>开发部</dname>
			<address>XX大厦-A910</address>
		</departement>
	</employee>
	<employee no="6302">
		<name>李铁柱</name>
		<age>32</age>
		<salary>9000</salary>
		<departement>
			<dname>销售部</dname>
			<address>XX大厦-A203</address>
		</departement>
	</employee>
</hr>

List<Node> nodes=document.selectNodes(xpathExp);这句程序取到的是根节点下的第一个节点吗?

写回答

1回答

好帮手慕柯南

2019-07-23

同学你好!

1.不是,是获取传入的节点下的所有子节点。由于departement是一个具有子几点的节点,所以与其他节点的方式获取会有点不同。

2.如果department节点下的dname,同学需要获取departement在获取dname,比如:

http://img.mukewang.com/climg/5d36d8ce00011afa08070096.jpg

如果我的回答解决了你的疑惑,请采纳,祝学习愉快~


0

0 学习 · 9666 问题

查看课程