共計 583 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用 @ 符號來獲取 XPath 屬性節點。例如,使用 @attribute_name 來獲取元素的屬性節點。
以下是一個示例,演示如何使用 XPath 獲取屬性節點:
from lxml import etree
# 創建一個 xml 字符串
xml_string = """
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>
"""
# 將 xml 字符串轉換為 Element 對象
root = etree.fromstring(xml_string)
# 使用 XPath 獲取屬性節點
category = root.xpath('//book/@category')
print(category)
輸出結果為:
['cooking']
在上述示例中,XPath 表達式 //book/@category 用于獲取名為 book 的元素的 category 屬性節點。使用 xpath() 函數執行 XPath 查詢,并將結果存儲在 category 變量中。最后,通過打印 category 變量來輸出結果。
丸趣 TV 網 – 提供最優質的資源集合!
正文完