Prevent lxml from escaping ampersand in `
` when writing to file

Viewed 389

I need to add an attribute to an existing XML element. This attribute must contain the & character inside an entity like 
. When writing the modified XML to a file the & becomes & and thus destroys the enttity.

import lxml.etree as et

e = et.Element("a")
e.set("attribute", "first line
second line
")
t = et.ElementTree(e)
t.write("test.xml")

# expected result
<a attribute="first line&#x0d;&#x0a;second line&#x0d;&#x0a;"/>

# actual result
<a attribute="first line&amp;#x0d;&amp;#x0a;second line&amp;#x0d;&amp;#x0a;"/>

How can I prevent lxml from escaping the & character when writing the XML to a file? I need the string &#x0d;&#x0a; to appear unescaped in the final XML file. Another application reading this modified XML file depends on the string &#x0d;&#x0a; appearing unmodified.

0 Answers
Related