Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract value of XML attribute in Python?

Tags:

python

xml

I need to extract the value of an attribute in an XML document using Python.

For example, If I have an XML document like this:

<xml>
    <child type = "smallHuman"/>
    <adult type = "largeHuman"/>
</xml>

How would I be able get the text 'smallHuman' or 'largeHuman' to store in a variable?

Edit: I'm very new to Python and may require a lot of assistance.

This is what I've tried so far:

#! /usr/bin/python

import xml.etree.ElementTree as ET


def walkTree(node):
    print node.tag
    print node.keys()
    print node.attributes[]
    for cn in list(node):
        walkTree(cn)

treeOne = ET.parse('tm1.xml')
treeTwo = ET.parse('tm3.xml')

walkTree(treeOne.getroot())

Due to the way this script will be used, I cannot hard-code the XML into the .py file.

like image 573
Alex Ritchie Avatar asked Feb 12 '18 12:02

Alex Ritchie


2 Answers

To get the attribute value from an XML, you can do like this:

import xml.etree.ElementTree as ET

xml_data = """<xml>
<child type = "smallHuman"/>
<adult type = "largeHuman"/>
</xml>"""

# This is like ET.parse(), but for strings
root = ET.fromstring(xml_data)

for a child in root:
    print(child.tag, child.attrib)

You can find more details and examples on the link below: https://docs.python.org/3.5/library/xml.etree.elementtree.html

like image 101
pafreire Avatar answered Sep 18 '22 23:09

pafreire


Using ElementTree you can use find method & attrib .

Example:

import xml.etree.ElementTree as ET

z = """<xml>
    <child type = "smallHuman"/>
    <adult type = "largeHuman"/>
</xml>"""


treeOne = ET.fromstring(z)
print treeOne.find('./child').attrib['type']
print treeOne.find('./adult').attrib['type']

Output:

smallHuman
largeHuman
like image 28
Rakesh Avatar answered Sep 19 '22 23:09

Rakesh