How to set the content of a markup called "text" with lxml.objectify?

151 Views Asked by At

I am trying to parse an XML File in python with lxml.objectify, modify the text from <ns:text> and then put back together the XML.

This is a short overview of my XML file:

<ns:map xmlns:ns="...">
    <ns:topics>
        <ns:topic>
            <ns:text>HI</ns:text>
        </ns:topic>
        <ns:topic>
            <ns:text>HELLO</ns:text>
        </ns:topic>
    </ns:topics>
</ns:map>

I parsed the XML and retrieved the topic in topics. I tried to change the "HI" text into "test" for <ns:text> in the first topic.

from lxml import objectify as obj
from lxml import etree

root= obj.parse(xmlFileName)
root.topics.topic[0].text = 'test'
obj_xml= etree.tostring(root, encoding="unicode", pretty_print=True)
print(obj_xml)

I supposed this would be the outcome:

<ns:map xmlns:ns="...">
    <ns:topics>
        <ns:topic>
            <ns:text>test</ns:text>
        </ns:topic>
        <ns:topic>
            <ns:text>HELLO</ns:text>
        </ns:topic>
    </ns:topics>
</ns:map>

but the .text is a read-only attribute and not my <ns:text>. I can't access my <ns:text> to change the text.

I have been reading a lot of tutorials with lxml.objectify but I can't find something similar to my problem.

PS: I cannot change the name of the markup. It's a generated XML.

Thank you, Elena

1

There are 1 best solutions below

0
On

I found the answer. I can access and change my text doing this:

root.topics.topic[0]["text"] = "test"