What is the best (re: easiest) way to read a value from an xml file using python? I'm a novice, and have tried to play around with minidom, but am not sure of how to format the script.
The XML in /tmp/text.xml:
<computer>
<location>
<username>FirsLast</username>
</location>
</computer>
I want to parse the username and use it as a variable.
Here's what I've tried:
#!/usr/bin/python
import xml.dom.minidom as minidom
doc = minidom.parse('/tmp/text.xml')
location = doc.getElementsByTagName('location')[0]
username = location.getAttribute('username')
print(username)
I don't get any results at all. I'd expect to see FirsLast
.
From the top of my head:
import xml.dom.minidom as minidom
doc = minidom.parse('/tmp/tes.xml')
location = doc.getElementsByTagName('location')[0]
# If I recall carriage return and spaces are text nodes so we
# need to skip those
username = list(filter(lambda x: x.nodeType == minidom.Node.ELEMENT_NODE, location.childNodes))
print(username[0].firstChild.nodeValue)
You're assuming that username
is an attribute of location
and it's not. It's a child node and it contains another child note which is the text. Minidom is quite cumbersome, so unless you really have to work with it (security reasons comes to mind) I'll advice you to use xml.etree.ElementTree
UPDATE
Op requested an example using ET:
import xml.etree.ElementTree as ET
sample = """
<computer>
<location>
<username>FirsLast</username>
</location>
</computer>
"""
doc = ET.fromstring(sample)
username = doc.findall('./location/username')
print(username[0].text)