如何使用 Python ElementTree 提取 xml 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4573237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:23:14  来源:igfitidea点击:

How to extract xml attribute using Python ElementTree

pythonxmlxpathelementtree

提问by Will Curran

For:

为了:

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

How do I get "value"?

我如何获得“价值”?

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

Throws an error.

抛出错误。

采纳答案by unutbu

This will find the first instance of an element named barand return the value of the attribute 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'

回答by unutbu

Your expression:

你的表情:

./bar[@key]

./bar[@key]

It means: barchildren having keyattribute

这意味着:bar孩子有key属性

If you want to select the attribute, use this relative expression:

如果要选择属性,请使用以下相对表达式:

bar/@key

It means: the keyattribute of barchildren

意思是:孩子key属性bar

Of course, you need to consider to use a fully compliant XPath engine like lxml.

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

回答by rashok

Getting child tag's attribute value in a XML using ElementTree

使用 ElementTree 在 XML 中获取子标签的属性值

Parse the XML file and get the roottag and then using [0]will give us first child tag. Similarly [1], [2]gives us subsequent child tags. After getting child tag use .attrib[attribute_name]to get value of that attribute.

解析 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'

If the xml content is in file. You should do below task to get the root.

如果 xml 内容在文件中。您应该执行以下任务以获取root.

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

回答by dipenparmar12

By following method you can get all attributes from xml (in Dictionary)

通过以下方法,您可以从 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)