parsing xml file with similar tags and different attributes!
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
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)
精彩评论