tags:

views:

33

answers:

1

I am sorry if this is a repeated question or a basic one as I am new to Python. I am trying to parse the following XML commands so that I can "extract" the tag value for Daniel and George. I want the answer to look like Daniel = 78, George = 90.

<epas:property name="Tom">12</epas:property>
<epas:property name="Alice">34</epas:property>
<epas:property name="John">56</epas:property>
<epas:property name="Danial">78</epas:property>
<epas:property name="George">90</epas:property>
<epas:property name="Luise">11</epas:property>

The xml commands are stored in one string. i.e. myString so here is the first part of code that I tried to parse this string (myString):

element = xml.dom.minidom.parseString(myString).getElementByTagName ("epas:property")
if not element:
   print "error message"
else:
    for el in element:
        value [el.getAttribute("name")] = el.firstChild.data

I tried to reference Daniel and George to the array index to get the value but looks I am not doing it correctly. I would appreciate your ideas/comments on this.

Cheers, Bill

+1  A: 

Don't use xml.dom.minidom, it's a terrible library! Use ElementTree or lxml (ElementTree is in the standard library and will probably work fine for you).

You should have an XML namespace, i.e., something like xmlns:epas="http://something". Also you can't have bare elements, they need to be enclosed. If you have "fake" namespaces (i.e., no declaration) you could punt and do:

myString = '<doc xmlns:epas="dummy">%s</doc>' % myString

With ElementTree it's something like this:

import xml.etree.ElementTree as ET
doc = ET.fromstring(myString)
result = {}
for el in doc.findall('{http://something}property):
    result[el.get('name')] = int(el.text)
Ian Bicking
Thanks Ian. I have Python 2.5.4 version installed but I am getting: "No Module named etree.ElementTree as ET". As you said ElenetTree is in the standard library so should work with Python 2.5.4! Am I missing something here? :-)
Bill Jordan
2.5 should include ElementTree. On some operating systems it *might* be a separate installation (i.e., the packager split it out of the standard library). You can also just install ElementTree then do `import ElementTree as ET`.
Ian Bicking