本文介紹了使用 Python 2 在 XML 中按屬性查找所有節點的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個 XML 文件,其中包含許多具有相同屬性的不同節點.
I have an XML file which has a lot of different nodes with the same attribute.
我想知道是否可以使用 Python 和任何其他包(如 minidom 或 ElementTree)找到所有這些節點.
I was wondering if it's possible to find all these nodes using Python and any additional package like minidom or ElementTree.
推薦答案
可以使用內置的xml.etree.ElementTree
模塊.
You can use built-in xml.etree.ElementTree
module.
如果您希望所有元素都具有特定屬性而不考慮屬性值,則可以使用 xpath 表達式:
If you want all elements that have a particular attribute regardless of the attribute values, you can use an xpath expression:
//tag[@attr]
或者,如果您關心價值觀:
Or, if you care about values:
//tag[@attr="value"]
示例(使用 <代碼>findall() 方法):
Example (using findall()
method):
import xml.etree.ElementTree as ET
data = """
<parent>
<child attr="test">1</child>
<child attr="something else">2</child>
<child other_attr="other">3</child>
<child>4</child>
<child attr="test">5</child>
</parent>
"""
parent = ET.fromstring(data)
print [child.text for child in parent.findall('.//child[@attr]')]
print [child.text for child in parent.findall('.//child[@attr="test"]')]
打印:
['1', '2', '5']
['1', '5']
這篇關于使用 Python 2 在 XML 中按屬性查找所有節點的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!