following-sibling
是一个XPath(XML Path Language)轴,用于选择当前节点之后的所有兄弟节点。在XML文档中,节点可以有子节点、父节点和兄弟节点。兄弟节点是指与当前节点具有相同父节点的其他节点。following-sibling
轴允许你选择当前节点之后的所有这些兄弟节点。
/root/element
。./following-sibling::*
。following-sibling
轴提取特定节点之后的所有兄弟节点。假设我们有以下XML文档:
<library>
<book id="1">
<title>Book 1</title>
<author>Author 1</author>
</book>
<book id="2">
<title>Book 2</title>
<author>Author 2</author>
</book>
<book id="3">
<title>Book 3</title>
<author>Author 3</author>
</book>
</library>
如果我们想选择第一个<book>
元素之后的所有<book>
元素,可以使用以下XPath表达式:
from lxml import etree
xml_data = """
<library>
<book id="1">
<title>Book 1</title>
<author>Author 1</author>
</book>
<book id="2">
<title>Book 2</title>
<author>Author 2</author>
</book>
<book id="3">
<title>Book 3</title>
<author>Author 3</author>
</book>
</library>
"""
tree = etree.fromstring(xml_data)
books_after_first = tree.xpath("//book[1]/following-sibling::book")
for book in books_after_first:
print(etree.tostring(book, pretty_print=True).decode())
问题:在使用following-sibling
轴时,可能会遇到选择不到预期节点的情况。
原因:
解决方法:
例如,如果XML文档使用了命名空间:
<library xmlns="http://example.com/library">
<book id="1">
<title>Book 1</title>
<author>Author 1</author>
</book>
<book id="2">
<title>Book 2</title>
<author>Author 2</author>
</book>
<book id="3">
<title>Book 3</title>
<author>Author 3</author>
</book>
</library>
可以使用以下XPath表达式:
namespaces = {"ns": "http://example.com/library"}
books_after_first = tree.xpath("//ns:book[1]/following-sibling::ns:book", namespaces=namespaces)
通过这种方式,可以正确处理带有命名空间的XML文档。
领取专属 10元无门槛券
手把手带您无忧上云