简体   繁体   English

XML 换行符实体和 Python 编码

[英]XML line break character entity and Python encoding

I have the following line of code in a python script:我在 python 脚本中有以下代码行:

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 &我想在 XML 输出中看到这个字符实体,但第一个 & 符号不断被&替换& character entity, which creates the nonsense character entity 
字符实体,它创建无意义的字符实体
 . .

I am encoding the file as utf-8 .我将文件编码为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.我正在尝试实施@mzjn 指出的此处找到的解决方案。

How to output XML entity references 如何输出 XML 实体引用

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.我没有收到任何错误,但结果与我write树时的结果没有任何不同。

Again I am stuck.我又被卡住了。

What I eventually did was use the standard Python write function instead of using ElementTree's own write function.我最终做的是使用标准的 Python write函数,而不是使用 ElementTree 自己的write函数。

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.以上是Python代码的最后一步。 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.它可能会更慢,但它对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM