I certain this type of question has been asked before, but I can't seem to get the right set of words to find the answer myself...
I've got an XML file, for example
<document>
<page>
<title>title1</title>
<id>1</id>
<text>this is text1</text>
</page>
<page>
<title>title2</title>
<id>2</id>
<text>this is text2</text>
</page>
<page>
<title>title3</title>
<id>3</id>
<comment>random comment</comment>
<text>this is text3</text>
</page>
</document>
I am trying to find a way to, ideally, store each values within tags into an array.
Now I had originally tried just printing everything with the code below, but that only worked until the time where there is the random tag which throws off the indexing. So, is there a way to simple get the text from tag? Or is there an absolute need to know the array index?
import xml.etree.ElementTree as ET
tree = ET.parse('./xml_file.xml')
root = tree.getroot()
for child in root:
print(child[2].text)
I apologies if this is common question, I really couldn't figure out any answers online.
Since from your question it sounds like you're looking to get a specific key, you can simple use find(<key_name>).text
to get the contents of the XML key with that name
import xml.etree.ElementTree as ET
tree = ET.parse('./all_foods.xml')
root = tree.getroot()
for x in root:
print(x.find("title").text)
>>>
title1
title2
title3