【问题标题】:XML line break character entity and Python encodingXML 换行符实体和 Python 编码
【发布时间】:2019-07-04 18:35:17
【问题描述】:

我在 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;&amp;#x0A;#if (lg_quality = 3)&amp;#x0A;#declare lg_quality = 4;&amp;#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;&&#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;', '&')

我没有收到任何错误,但结果与我之前write 树时没有任何不同。

我又卡住了。

【问题讨论】:

  • 您是否尝试过在 python 文件中添加编码声明? (文件开头# -*- coding: utf-8 -*-
  • 我刚试过,但没有帮助。
  • 非常相似的问题:stackoverflow.com/q/7986272/407651
  • 问题完全一样。然而,解决方案只有一个建议。
  • 我找到了解决方案,有机会会发布。

标签: python xml elementtree


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 2023-03-31
    • 2011-08-25
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多