自动化测试面试题 - 解释XPath绝对路径和相对路径?
1. XPath简介
XPath(XML Path Language)是一种在XML文档中查找信息的语言,它使用路径表达式来选取XML文档中的节点或节点集。XPath是XSLT和XQuery的主要组成部分,在Web爬虫和数据抽取中也有广泛应用。
在XPath中,路径可以分为两种主要类型:绝对路径和相对路径。理解这两种路径的区别对于有效地使用XPath至关重要。
2. 绝对路径
2.1 绝对路径定义
绝对路径是从根节点开始的完整路径,它总是以斜杠/开头,表示从文档的根开始导航。
flowchart TD
A[根节点 /] --> B[html]
B --> C[body]
C --> D[div]
D --> E[p]
2.2 绝对路径特点
- 总是从根节点开始
- 路径以单斜杠
/开头 - 结构固定,不受当前节点影响
- 如果文档结构变化,路径可能失效
2.3 Java代码示例
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathConstants;
public class XPathAbsoluteExample {
public static void main(String[] args) throws Exception {
// 创建DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// 解析XML文档
Document document = builder.parse("example.xml");
// 创建XPath对象
XPath xPath = XPathFactory.newInstance().newXPath();
// 使用绝对路径查询
String expression = "/html/body/div/p";
NodeList nodes = (NodeList) xPath.compile(expression)
.evaluate(document, XPathConstants.<


1721

被折叠的 条评论
为什么被折叠?



