Sreeni Puthiyillam
Sreeni Puthiyillam

Reputation: 485

Iterate through XML to get all child nodes text value

i have a xml with following data. i need to get value of and all other attribute. i return a python code there i get only first driver value.

My xml :

<volume name="sp" type="span" operation="create">
    <driver>HDD1</driver>
    <driver>HDD2</driver>
    <driver>HDD3</driver>
    <driver>HDD4</driver>
</volume>

My script:

import xml.etree.ElementTree as ET
doc = ET.parse("vol.xml")
root = doc.getroot() #Returns the root element for this tree.
root.keys()          #Returns the elements attribute names as a list. The names are returned in an arbitrary order
root.attrib["name"]
root.attrib["type"]
root.attrib["operation"]

print root.get("name")
print root.get("type")
print root.get("operation")

for child in root:
    #print child.tag, child.attrib
    print root[0].text

My output:

    sr-query:~# python volume_check.py aaa
    sp
    span
    create
    HDD1
   sr-queryC:~#

I am not get HDD2, HDD3 and HDD4. How to itirate through this xml to get all values? Any optimized way? I think any for loop can do that but not familiar with Python.

Upvotes: 0

Views: 4040

Answers (1)

iMom0
iMom0

Reputation: 12931

In your for loop, it should be

child.text

not

root[0].text

Upvotes: 4

Related Questions