How to extract xml attribute using Python ElementTree

前端 未结 4 742
一向
一向 2020-12-08 13:39

For:


 text

How do I get \"value\"?

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


        
4条回答
  •  广开言路
    2020-12-08 14:01

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

    Parse the XML file and get the root tag 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.

    >>> import xml.etree.ElementTree as ET
    >>> xmlstr = 'text'
    >>> 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.

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

提交回复
热议问题