web-dev-qa-db-ja.com

Python ElementTreeを使用してxml属性を抽出する方法

にとって:

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

「値」を取得するにはどうすればよいですか?

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

エラーをスローします。

29
Will Curran

これにより、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'
43
unutbu

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()
2
rashok

あなたの表現:

./bar[@key]

意味:barkey属性を持つ子

属性を選択する場合は、次の相対式を使用します。

bar/@key

つまり、key childrenのbar属性

もちろん、 lxml のような完全に準拠したXPathエンジンを使用することを検討する必要があります。

1
user357812

次のメソッドにより、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)
0
Dipen Parmar