0

I have the following line of code in a python script:

dep11 = ET.SubElement(dep1, "POVCode").text = "#declare lg_quality = LDXQual;
#if (lg_quality = 3)
#declare lg_quality = 4;
#end"

My question is in regards to the 
 character. I want to see this character entity in the XML output, but the first ampersand keeps getting replaced with the & character entity, which creates the nonsense character entity 
.

I am encoding the file as utf-8.

import xml.etree.ElementTree as ET

...

with open("LGEO.xml", "wb") as f:
    tree.write(f, "utf-8")

And I end up with:

<POVCode>#declare lg_quality = LDXQual;&amp;#x0A;#if (lg_quality = 3)&amp;#x0A;#declare lg_quality = 4;&amp;#x0A;#end</POVCode>

Not sure what I'm doing wrong.

[edit]

I am trying to implement the solution found here that @mzjn pointed out.

How to output XML entity references

I have six lines of code:

dep11 = ET.SubElement(dep1, "POVCode")
dep21 = ET.SubElement(dep2, "POVCode")
dep11.text = "#declare lg_quality = LDXQual;&&#x0A;#if (lg_quality = 3)&&#x0A;#declare lg_quality = 4;&&#x0A;#end"
dep21.text = "#declare lg_studs = LDXStuds;&&#x0A;"
ET.tostring(dep11).replace('&amp;&amp;', '&')
ET.tostring(dep21).replace('&amp;&amp;', '&')

I get no error, but the result is not any different than before when I write the tree.

Again I am stuck.

6
  • Have you tried adding encoding declaration to the python file? (# -*- coding: utf-8 -*- at the beginning of the file) Commented Jul 4, 2019 at 18:44
  • I just tried that but it didn't help. Commented Jul 4, 2019 at 18:46
  • Very similar question: stackoverflow.com/q/7986272/407651 Commented Jul 6, 2019 at 5:39
  • The issue is exactly the same. There's only the one suggestion of a solution however. Commented Jul 6, 2019 at 5:45
  • I found a solution and will post it when I get a chance. Commented Jul 7, 2019 at 6:24

1 Answer 1

0

What I eventually did was use the standard Python write function instead of using ElementTree's own write function.

text = ET.tostring(root).replace("&amp;&amp;", "&")

with open("LGEO.xml", "wb") as f:
    f.write(text.encode("utf-8"))

The above is the last step in the Python code. I don't know if there are disadvantages to converting the root object to a string like this. It could be slower but it works for me.

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.