0

I'm struggling to find a good example of how one would add an XML Element to an XML Document and also add the data (inner-text) to this same element, but wrap the data in CDATA tags?

Here is an example of what I need. I have the following document.

<data>
     <config>
          <documentation>This is my documentation<documentation>
     </config>
</data>

I then want to add a element and CDATA as the inner-text. So it would look something like this. The data that I need to wrap in CDATA tags can be fairly large and will need to be read/referenced from file.

<data>
     <config>
              <documentation>This is my documentation<documentation>
              <script><![CDATA[
              function foo()
              …
              End
              ]]>
              </script>
     </config>
</data>

I then need to write the changes out to a new document... (so that I have the original and the additions.

1

1 Answer 1

1

You should be able to use the .CDATA() method provided by lxml.

http://lxml.de/api.html#cdata

Just create a SubElement as normal

some_var = root.find('config')
another_var = etree.SubElement(some_var, 'script')
another_var.text = etree.CDATA(another_var.text)

Then you can write the data out as normal.

Sign up to request clarification or add additional context in comments.

Comments

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.