簡體   English   中英

如何使用 Python ElementTree 提取 xml 屬性

[英]How to extract xml attribute using Python ElementTree

為了:

<foo>
 <bar key="value">text</bar>
</foo>

我如何獲得“價值”?

xml.findtext("./bar[@key]")

引發錯誤。

這將找到名為bar的元素的第一個實例並返回屬性key的值。

In [52]: import xml.etree.ElementTree as ET

In [53]: xml=ET.fromstring(contents)

In [54]: xml.find('./bar').attrib['key']
Out[54]: 'value'

使用 ElementTree 在 XML 中獲取子標簽的屬性值

解析 XML 文件並獲取root標簽,然后使用[0]將給我們第一個子標簽。 類似地[1], [2]為我們提供了后續的子標簽。 獲取子標簽后,使用.attrib[attribute_name]獲取該屬性的值。

>>> import xml.etree.ElementTree as ET
>>> xmlstr = '<foo><bar key="value">text</bar></foo>'
>>> root = ET.fromstring(xmlstr)
>>> root.tag
'foo'
>>> root[0].tag
'bar'
>>> root[0].attrib['key']
'value'

如果 xml 內容在文件中。 您應該執行以下任務以獲取root

>>> tree = ET.parse('file.xml')
>>> root = tree.getroot()

你的表情:

./bar[@key]

這意味着:具有key屬性的bar子級

如果要選擇屬性,請使用以下相對表達式:

bar/@key

意思是: bar children的key屬性

當然,您需要考慮使用完全兼容的 XPath 引擎,例如lxml

通過以下方法,您可以從 xml 中獲取所有屬性(在字典中)

import xml.etree.ElementTree as etree
xmlString= "<feed xml:lang='en'><title>World Wide Web</title><subtitle lang='en'>Programming challenges</subtitle><link rel='alternate' type='text/html' href='http://google.com/'/><updated>2019-12-25T12:00:00</updated></feed>"
xml= etree.fromstring(xmlString)  

def get_attr(xml):
    attributes = []
    for child in (xml):
        if len(child.attrib)!= 0:
            attributes.append(child.attrib)
        get_attr(child)
    return attributes
attributes = get_attr(xml)

print(attributes)

dipenparmar12 函數不會返回孩子的子屬性。 因為該函數是遞歸的,所以每次調用的屬性列表都將設置為一個空列表。 此函數將返回孩子的孩子。

import xml.etree.ElementTree as etree
xml= etree.fromstring(xmlString) 


 def get_attr(xml, attributes):
     for child in (xml):
         if len(child.attrib)!= 0:
             attributes.append(child.attrib)
         get_attr(child,attributes)
     return attributes

  attributes = get_attr(xml,[])
  print(attributes)

為了更深入地了解樹,可以使用這種類型的函數。

root[1][2][0].tag  # For displaying the nodes
root[1][2][0].text # For showing what's inside the node

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM