I have a XML file like this:
and I want to iterate through it to print out the temperature every time the tag is <temperature>
.
Is there any functions built into xml.etree.ElementTree or lxml or other libraries I can use to do this?
Here's my current effort but that just prints all of the elements
CodePudding user response:
One of the best ways to process XML is with XPath. lxml has better support as ElementTree's XPath support is limited. But either one would work in your example.
Here's an example using lxml:
from lxml import etree
tree = etree.parse("dub_airport.xml")
for temp in tree.xpath(".//temperature"):
print(f"The temperature value is \"{temp.text}\".")
If you really need to iterate (like if your XML is very large and you have memory issues), you can use something like iter()
or iterparse()
.
Here's an example using iterparse() in lxml:
from lxml import etree
for event, elem in etree.iterparse("dub_airport.xml", tag="temperature", events=("start",)):
print(f"The temperature value is \"{elem.text}\".")
elem.clear()
CodePudding user response:
To iterate until a specific tag name you should loop in root and use .tag
instance to compare if it is equal to 'temperature'
in this case, for a simple case I have display some values by using tag
, attrib
and text
objects.
>>> for child in root:
... for child_tag in child:
... if (child_tag.tag == 'temperature'):
... print(child_tag.tag, child_tag.attrib, child_tag.text)
...
output:
temperature {} 11
temperature {} 11
temperature {} 11