Skip to content Skip to sidebar Skip to footer

Find And Replace Cdata Attribute Values In Xml - Python

I am attempting to demonstrate functionality for finding/replacing XML attributes, similar to that posed in a related question (Find and Replace XML Attributes by Indexing - Python

Solution 1:

Since the CDATA is an HTML string, I would extract it out of the XML, make changes to it and then reinsert it in the xml:

#first editcd = etree.fromstring(doc.xpath('//*[local-name()="description"]')[0].text) #out of the XML

vals = ["1900","2000","3000","4000"]
rems = ["Source","1800","1100","1500"]
targets = cd.xpath('//tr//td')
for target in targets:
    if target.text in rems:
        target.text=vals[rems.index(target.text)]
#second edit
doc.xpath('//*[local-name()="description"]')[0].text = etree.CDATA(etree.tostring(cd)) #... and back into the XML as CDATAprint(ET.tostring(tree).decode())

The output should be your expected output.

Post a Comment for "Find And Replace Cdata Attribute Values In Xml - Python"