繁体   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