How Do I Change Variables in CDATA section of an XML document?

I have an XML file containing a CDATA section, for example :

<?xml version="1.0" encoding="UTF-8"?>
<Header>
	<Test1>Hello</Test1>
</Header>
<MsgPayload><![CDATA[<?xml version="1.0" encoding="UTF-8" ?><Test>1234</Test>]]></MsgPayload>
<Footer>
	<MessageID>String</MessageID>
</Footer>

I’m trying to work out a way that I can read and change the node of Test in the CDATA section but it proving difficult.
First off I would like to be able to read the ‘1234’ as an output, secondly I would like to be able to replace that value and be able to read that out too.
There will be hundreds of these nodes in the actual work that I am doing so is there an easy way of doing this?
I have tried multiple different ways but have not been able to get anywhere with it…

Thanks for any help provided.

Hard to answer specifically with the limited example, but I would open the file in a text editor (or some other program) then use Eggplant to use that program as a user would. Meaning, scrolling looking for instances of the item you are looking for, reading the text from the found locations into variables, manipulating then as needed, then changing them back in the original document as needed.

Hello @dankadamski,

Working with CDATA sections in XML can be tricky, but I’ll guide you through the process.
To read the value within the CDATA section, you’ll need to extract the content from the element.
The content inside the CDATA section is treated as plain character data, so you can access it directly.
To replace the value ‘1234’, you’ll need to modify the content within the CDATA section.
You can achieve this by updating the text inside the CDATA node.
Since you mentioned there will be hundreds of these nodes, consider using a loop or an appropriate mechanism to process each one.
Iterate through the nodes and apply the necessary changes.

import xml.etree.ElementTree as ET

# Load your XML content (replace with your actual XML content)
xml_content = """
<?xml version="1.0" encoding="UTF-8"?>
<Header>
    <Test1>Hello</Test1>
</Header>
<MsgPayload><![CDATA[<?xml version="1.0" encoding="UTF-8" ?><Test>1234</Test>]]></MsgPayload>
<Footer>
    <MessageID>String</MessageID>
</Footer>
"""

# Parse the XML
root = ET.fromstring(xml_content)

# Find the CDATA section
msg_payload_cdata = root.find(".//MsgPayload")

# Read the content (1234)
original_value = msg_payload_cdata.text
print(f"Original value: {original_value}")

# Replace the value  
new_value = "5678"
msg_payload_cdata.text = f"<![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Test>{new_value}</Test>]]>"

# Verify the change
updated_value = msg_payload_cdata.text
print(f"Updated value: {updated_value}")

Remember to replace the xml_content variable with your actual XML data. This example demonstrates how to read and replace the value within the CDATA section.

Best Regards,