0

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

1 Answer 1

1
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 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.