user3833794 user3833794 - 1 year ago 258
Python Question

Python read data from XML file

I use minidom to read my XML files but with the following example this is not working. I have an error message:

I would to retrieve the value in

tag (
) but I have an error.

This is the code:

from xml.dom import minidom

docXML = minidom.parse('/root/Desktop/tpage.xml')
node = docXML.getElementsByTagName('span')[0]

This is the content of

<span class="lp">

<span sys:innerhtml="{binding Last}"

sys:codeafter="$.quotebroker.setTitleProperties($dataItem, 'Last')">




and this is the error message:

File "", line 5, in <module>
dom = parse('/root/Desktop/bot/tpage.xml')
File "/usr/lib/python2.7/xml/dom/", line 1920, in parse
return expatbuilder.parse(file)
File "/usr/lib/python2.7/xml/dom/", line 924, in parse
result = builder.parseFile(fp)
File "/usr/lib/python2.7/xml/dom/", line 207, in parseFile
parser.Parse(buffer, 0)
xml.parsers.expat.ExpatError: unbound prefix: line 2, column 0

Answer Source

The shown XML isn't valid because it uses a namespace prefix (sys) but doesn't define it and the XML parser (xml.dom.expatbuilder module) chokes on that. You would have to go straight to the expatbuilder in order to give its parse() function the argument to ignore namespaces. And if you want to extract the text node in the second <span> your index is off by one:

from xml.dom import expatbuilder

def main():
    document = expatbuilder.parse('test.xml', False)
    node = document.getElementsByTagName('span')[1]
    print float(

if __name__ == '__main__':
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download