Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding xml text content from tag name in python

Tags:

python

xml

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.

like image 204
Ronan Avatar asked Jul 24 '26 16:07

Ronan


1 Answers

import xml.etree.ElementTree as ET
tree = ET.parse('./all_foods.xml')
my_text = [item.text for item in tree.iter()]

This will give you list of text that you want. If you want some specific text you can use

my_tags = [item.text for item in tree.iter() if item.text == "title1"]
like image 181
nick_gabpe Avatar answered Jul 27 '26 06:07

nick_gabpe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!