XML换行字符实体和Python编码
XML line break character entity and Python encoding
我在 python 脚本中有以下代码行:
dep11 = ET.SubElement(dep1, "POVCode").text = "#declare lg_quality = LDXQual;
#if (lg_quality = 3)
#declare lg_quality = 4;
#end"
我的问题是关于 

角色的。我想在 XML 输出中看到这个字符实体,但第一个 & 符号不断被 &
字符实体替换,这会创建无意义的字符实体 

.
我正在将文件编码为 utf-8
。
import xml.etree.ElementTree as ET
...
with open("LGEO.xml", "wb") as f:
tree.write(f, "utf-8")
最后我得到:
<POVCode>#declare lg_quality = LDXQual;&#x0A;#if (lg_quality = 3)&#x0A;#declare lg_quality = 4;&#x0A;#end</POVCode>
不确定我做错了什么。
[编辑]
我正在尝试实施@mzjn 指出的此处找到的解决方案。
How to output XML entity references
我有六行代码:
dep11 = ET.SubElement(dep1, "POVCode")
dep21 = ET.SubElement(dep2, "POVCode")
dep11.text = "#declare lg_quality = LDXQual;&
#if (lg_quality = 3)&
#declare lg_quality = 4;&
#end"
dep21.text = "#declare lg_studs = LDXStuds;&
"
ET.tostring(dep11).replace('&&', '&')
ET.tostring(dep21).replace('&&', '&')
我没有收到任何错误,但结果与我 write
树时的结果没有任何不同。
我又卡住了。
我最终做的是使用标准 Python write
函数而不是使用 ElementTree 自己的 write
函数。
text = ET.tostring(root).replace("&&", "&")
with open("LGEO.xml", "wb") as f:
f.write(text.encode("utf-8"))
以上是Python代码的最后一步。我不知道像这样将根对象转换为字符串是否有缺点。它可能会慢一些,但对我有用。
我在 python 脚本中有以下代码行:
dep11 = ET.SubElement(dep1, "POVCode").text = "#declare lg_quality = LDXQual;
#if (lg_quality = 3)
#declare lg_quality = 4;
#end"
我的问题是关于 

角色的。我想在 XML 输出中看到这个字符实体,但第一个 & 符号不断被 &
字符实体替换,这会创建无意义的字符实体 &#x0A;
.
我正在将文件编码为 utf-8
。
import xml.etree.ElementTree as ET
...
with open("LGEO.xml", "wb") as f:
tree.write(f, "utf-8")
最后我得到:
<POVCode>#declare lg_quality = LDXQual;&#x0A;#if (lg_quality = 3)&#x0A;#declare lg_quality = 4;&#x0A;#end</POVCode>
不确定我做错了什么。
[编辑]
我正在尝试实施@mzjn 指出的此处找到的解决方案。
How to output XML entity references
我有六行代码:
dep11 = ET.SubElement(dep1, "POVCode")
dep21 = ET.SubElement(dep2, "POVCode")
dep11.text = "#declare lg_quality = LDXQual;&
#if (lg_quality = 3)&
#declare lg_quality = 4;&
#end"
dep21.text = "#declare lg_studs = LDXStuds;&
"
ET.tostring(dep11).replace('&&', '&')
ET.tostring(dep21).replace('&&', '&')
我没有收到任何错误,但结果与我 write
树时的结果没有任何不同。
我又卡住了。
我最终做的是使用标准 Python write
函数而不是使用 ElementTree 自己的 write
函数。
text = ET.tostring(root).replace("&&", "&")
with open("LGEO.xml", "wb") as f:
f.write(text.encode("utf-8"))
以上是Python代码的最后一步。我不知道像这样将根对象转换为字符串是否有缺点。它可能会慢一些,但对我有用。