1

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>
6
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Oct 18, 2022 at 18:15
  • I need to make just a tag <recommendations> with all <text> tags inside. Commented Oct 18, 2022 at 18:21
  • How should the output look like? Please update the post. What did you try so far? Commented Oct 18, 2022 at 18:23
  • Output: <recommendations> Text.Text2. </recommendations> Commented Oct 18, 2022 at 19:17
  • I tried 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) Commented Oct 18, 2022 at 19:27

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

1 Comment

I think I'll need to use the get_text() 'cause I have more variables, that I don't write here... I just write my problem. but thanks I think it'll work, tomorrow I'll try that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.