简体   繁体   中英

lxml.etree not working with cdata in python 3

I want to change a value in XML file to CDATA with LXML.

It works perfectly when I simply change the text, but when CDATA is used, the content of the element is not replaced.

This is how I do the CDATA hack: https://blog.ionelmc.ro/2014/06/15/lxml-element-builder-and-cdata/

This is how I change a text value (between "RESPONSE" tags in XML shown below): Change text value with lxml

Question : How is it possible to change the content text of the RESPONSE tags to CDATA?

from lxml import etree
from lxml.builder import ElementMaker
from lxml.etree import CDATA


def add_cdata(element, cdata):
    assert not element.text, "Can't add a CDATA section. Element already has some text: %r" % element.text
    element.text = cdata

E = ElementMaker(typemap={
    CDATA: add_cdata
})

print("\nThe CDATA is working here perfectly: ")
print(etree.tostring(E.RESPONSE(CDATA('Some stuff that needs to be in a CDATA section'))))

tree = etree.fromstring('''<REQRES_MAPPING>
    <REQUEST>aaa</REQUEST>
    <RESPONSE>bbb</RESPONSE>
</REQRES_MAPPING>''')

print("\nThe data I need to change: ")
print(etree.tostring(tree))


response = tree.xpath("//RESPONSE")
if response:
    response[0].text = 'xxx'                   # this is working, but I need CDATA

print("\nThe text has changed between the RESPONSE tags: ")
print(etree.tostring(tree))


if response:
    response[0] = E.RESPONSE(CDATA('xxx'))     # this is not working

print("\nThis is not working here: ")
print(etree.tostring(tree))

What I want to get:

<REQRES_MAPPING>
    <REQUEST>aaa</REQUEST>
    <RESPONSE><![CDATA[yyy]]</RESPONSE>
</REQRES_MAPPING>

Obviously it's not a good method to insert the yyy with CDATA decoration, because at the end the LMXL will change CDATA's '<' and '>' tags to &lt; and &gt; .

By doing response[0] = ... you're just modyfying the list named response , you're not actually touching the tree at all.

You need:

tree.xpath("//RESPONSE")[0].text = CDATA('xxx')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM