Reputation: 165
I'm new to parsing xml files with Python. Could I get a little help on this one, if you dont mind.
Here is a snippet of my xml doc:
<xxxxx>
<xxxx name="xxxxx">
<xxxxx value="xxxxx"/>
<xxxxx value="xxxxxxxxxxx"/>
<xxxx>
<xxxxx>
<xxxx value="ReadWrite"/>
<Type value="XXXXX"/>
</xxxxx>
I just need to get the User name field. through out the file.
Here is my code that I have been working on:
import xml.etree.ElementTree as etree
xmlD = etree.parse("c:/Python27/doc.xml")
root = xmld.getroot()
for child in root:
for children in child:
print (children.txt)
print("\n")
I'm not a expert, just wondering if anyone has any ideas on how I could get that information. Any help is appreciated.
Upvotes: 1
Views: 52
Reputation: 10360
Once you have your root
element, you can find all your <User>
elements using the XPath selector './/User'
("select all User
elements found anywhere beneath the current element"), and then loop over them and get their name
attributes.
>>> [user.get('name') for user in root.findall('.//User')]
['admin']
Upvotes: 3