【转载】在Java中使用xpath对xml解析

想绕过xpath,其实很简单,看下面

https://www.cnblogs.com/vastsum/p/5940235.html

下面是一个小demo入门很详细(下面解析的是我用jsoup抓取的html页面)

//首先在dom4j中如何使用xpath技术导入xPath支持的jar包。jaxen-1.1-beta-6.jar
//(首先要先导dom4j包,dom4j下载地址:http://www.dom4j.org/dom4j-1.6.1/)。

运行截图:

源码:

package xpath;

import java.io.File;
import java.util.Iterator;
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;

/**
 * 读取下xml文档,获得document对象。 本文为xml连载第一篇,以下代码可以直接运行,结尾附上源码下载地址。
 */
class exmple {
	public static void main(String[] args) throws DocumentException {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File("./hh6.xml"));

		/**
		 * 节点对象的操作方法
		 */

		// 获取文档根节点
		Element root = document.getRootElement();
		// 输出根标签的名字
		System.out.println(root.getName());

		// 获取根节点下面的所有子节点(不包过子节点的子节点)
		List<Element> list = root.elements();
		// 遍历List的方法
		for (Element e : list) {
			System.out.println(e.getName());
		}

		// 获得指定节点下面的子节点
		Element contactElem = root.element("head");// 首先要知道自己要操作的节点。
		List<Element> contactList = contactElem.elements();
		for (Element e : contactList) {
			System.out.println("999" + e.getName());
		}

		// 调用下面获取子节点的递归函数。
		getChildNodes(root);
		System.out.println("子节点输出完毕");
		// 获得当前标签下指定名称的第一个子标签
		Element conElem = root.element("head");
		System.out.println(conElem.getName());

		// 获得更深层次的标签(一层一层的获取)
		Element nameElem = root.element("head").element("style");
		System.out.println(nameElem.getName());
	}

	// 递归查询节点函数,输出节点名称
	private static void getChildNodes(Element elem) {
		System.out.println(elem.getName()+elem.getPath());//重点:::并输出dom路径!!!
		Iterator<Node> it = elem.nodeIterator();
		while (it.hasNext()) {
			Node node = it.next();
			if (node instanceof Element) {
				Element e1 = (Element) node;
				getChildNodes(e1);
			}

		}
	}

}

猜你喜欢

转载自blog.csdn.net/qq_40374604/article/details/84453200