Parsing XML inner messages list using Python

Viewed 42

I am trying to parse the following messages and store them in a list using python. How can I store the messages in a list?

I reached the id and the language by the following code, but I need to find the messages.

import xml.etree.ElementTree as ET

tree = ET.parse(filename)
root = tree.getiterator()
print (root[0].attrib)

<?xml version="1.0" encoding="UTF-8" standalone="no"?><author id="1aa8c430-853b-4bbc-b784-df4c88264ccd" lang="en">
    <document><![CDATA[@username bahaha! unfortunately i'm not a tshirt person      ]]></document>
    <document><![CDATA[Mercy reunion at Olive Garden #traditions :)     ]]></document>
    <document><![CDATA[After 3 months of beating my head against a wall over this persuasion, I've finally had my "aha!" moment!! #progress! #improvement!      ]]></document>
</author>
2 Answers

Try:

import xml.etree.ElementTree as ET

tree = ET.parse("your_file.xml")
out = [d.text for d in tree.iter("document")]
print(out)

Prints:

[
    "@username bahaha! unfortunately i'm not a tshirt person      ",
    "Mercy reunion at Olive Garden #traditions :)     ",
    'After 3 months of beating my head against a wall over this persuasion, I\'ve finally had my "aha!" moment!! #progress! #improvement!      ',
]

First get the author tag from your root element:

tree = ET.parse(filename)
root = tree.getiterator()
author = root[0]

Then the language from the author tag's attrib:

author['lang']

...and the id:

author['id']

If you are storing the content of the author tag, you could create a dictionary to store the content of each author:

import xml.etree.ElementTree as ET

tree = ET.parse(filename)
root = tree.getiterator()

Iterate over the root elements and get the author tags

authors = []

for root in root:
    author = root.get('author')
    authors.append(author)

Get the language and id from the author tag

authors = {author['lang']:author['id'] for author in authors}

Iterate over the authors dictionary and print out the content

print(authors)

or

import xml.etree.ElementTree as ET
tree = ET.parse(filename)

root = tree.getiterator()
author = root[0]
lang = root.find('lang')
id = root.find('id')

print(author,lang,id)
Related