Reputation: 943
For each instrumentData in the below XML file, I need to print the id and the values in the data value=" " field. (the value between the quotes) All this using python 2.7
This is my XML file:
<instrumentDatas>
<instrumentData>
<instrument>
<id>Stephan</id>
</instrument>
<data value="A" />
<data value="B" />
<data value="C" />
</instrumentData>
<instrumentData>
<instrument>
<id>Patrick</id>
</instrument>
<data value="F" />
<data value="G" />
<data value="H" />
</instrumentData>
I am able to print the id for each instrumentData with the below code but cant figure out how to print the values.
from xml.dom import minidom
xmldoc=minidom.parse("C:/Users/Desktop/PythonXMLproject/Smallfile.xml")
instrumentDatas = xmldoc.getElementsByTagName("instrumentDatas")[0]
instrumentDatax= instrumentDatas.getElementsByTagName("instrumentData")
for instrumentData in instrumentDatax:
idx=instrumentData.getElementsByTagName("id")[0].firstChild.data
print(idx)
Thank you
Upvotes: 0
Views: 68
Reputation: 36
import xml.dom.minidom
DOMTree = xml.dom.minidom.parse("C:/Users/Desktop/PythonXMLproject/Smallfile.xml")
collection = DOMTree.documentElement
instrumentDatas = collection.getElementsByTagName("instrumentData")
for instrumentData in instrumentDatas:
idx = instrumentData.getElementsByTagName("id")[0].firstChild.data
print "ID: %s" % idx
datas = instrumentData.getElementsByTagName("data")
for data in datas:
if data.hasAttribute('value'):
value = data.getAttribute('value')
print "Value: %s" % value
Upvotes: 1