Reputation: 321
Here is an api xml i am working with:
<response>
<request>polaris</request>
<status>0</status>
<verbiage>OK</verbiage>
<object id="S251">
<type id="1">Star</type>
<name>α UMi</name>
<catId>α UMi</catId>
<constellation id="84">Ursa Minor</constellation>
<ra unit="hour">2.5301944</ra>
<de unit="degree">89.264167</de>
<mag>2.02</mag>
</object>
<object id="S251">
<type id="1">Star</type>
<name>α UMi</name>
<catId>α UMi</catId>
<constellation id="84">Ursa Minor</constellation>
<ra unit="hour">2.5301944</ra>
<de unit="degree">89.264167</de>
<mag>2.02</mag>
</object>
</response>
Here is my current code:
#!/usr/bin/env python
import xml.etree.ElementTree as ET
tree = ET.parse('StarGaze.xml')
root = tree.getroot()
callevent=root.find('polaris')
Moc1=callevent.find('polaris')
for node in Moc1.getiterator():
if node.tag=='constellation id':
print node.tag, node.attrib, node.text'
I want to be able to print defined children. For example:
constellation id=
ra unit=
Any help would be very much appreciated
Upvotes: 1
Views: 32
Reputation: 473853
Iterate over the object
nodes and locate the constellation
and ra
nodes using findall()
and find()
methods and .attrib
attribute:
import xml.etree.ElementTree as ET
tree = ET.parse('StarGaze.xml')
root = tree.getroot()
for obj in root.findall("object"):
constellation = obj.find("constellation")
ra = obj.find("ra")
print(constellation.attrib["id"], constellation.text, ra.attrib["unit"], ra.text)
Would print:
84 Ursa Minor hour 2.5301944
84 Ursa Minor hour 2.5301944
Upvotes: 1