XML换行符实体和Python编码 [英] XML line break character entity and Python encoding

查看:209
本文介绍了XML换行符实体和Python编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python脚本中有以下代码行:

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"

我的问题是关于
 字符的。我想在XML输出中看到该字符实体,但是第一个&号始终被& 字符实体所取代,该字符实体创建了无意义的字符实体


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 
.

我正在将文件编码为 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;&amp;#x0A;#if (lg_quality = 3)&amp;#x0A;#declare lg_quality = 4;&amp;#x0A;#end</POVCode>

不确定我在做什么错。

[edit]

我正在尝试实施@mzjn指出的解决方案。

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

如何输出XML实体引用

我有六行代码:

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.

我又被卡住了。

推荐答案

我最终要做的是使用标准的Python write 函数,而不是使用ElementTree自己的

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"))

以上是Python代码的最后一步。我不知道将根对象转换成这样的字符串是否有缺点。可能会慢一些,但对我有用。

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.

这篇关于XML换行符实体和Python编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆