XML Transform with Python

Question:

I have a XML file like this:

<recommendations>
    <para>
        <text>Text.</text>
    </para>
    <para>
        <text>Text2.</text>
    </para>
</recommendations>

I want to make a new recommendations tag with "Text" concatenate with "Text2" using python:
Text.Text2.

can someone help me?

I tried so far:

xml_parsed = ET.parse(file)
xml_parsed_root = xml_parsed.getroot()
recommendations_root = item.findall(r'recommendations')
for para in recommendations_root:
    for text in para:
        recommendations = ET.Element('recomendations')
        recommendations_root[text].text = text.text.append(recommendations)
    xml_root.append(item)

My expected Output:

<recommendations> Text.Text2. </recommendations>
Asked By: Thiago Oberle

||

Answers:

To solve this problem, I introduce a function get_text() which iterates through the root of the input and collect all texts. The rest would be easy:

from xml.etree import ElementTree as ET

def get_text(r):
    buffer = ""
    for para in r:
        for text in para:
            buffer += text.text
    return buffer

doc = ET.parse("data.xml")
root = doc.getroot()

out = ET.Element("recommendations")
out.text = get_text(root)
print(ET.dump(out))

Output:

<recommendations>Text.Text2.</recommendations>

Update

Instead of writing get_text(), you can also use Xpath:

out = ET.Element("recommendations")
out.text = "".join(node.text for node in root.findall(".//text"))
print(ET.dump(out))
Answered By: Hai Vu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.