首页 > 解决方案 > 将 ElementTree 树写入磁盘时如何保留 html 标签?

问题描述

我正在尝试使用 Python 的 xml.etree.ElementTree 将 XML 树写入磁盘,以重现给我的示例文档。目标 XML 文档中的字段如下所示:

<title>
This is a test of <br/> Hershey's <sup>&$174;</sup> chocolate factory machine <br/>
</title>

我的问题是,每当我尝试使用 ElementTree 的方法将文本写入磁盘时,.write()我都无法实现上述输出。html 标签将被转换为&lt;br&gt;或商标符号(® 的东西)将显示为实际符号。有没有办法对我的文本进行编码以获得上述输出(其中商标由 ® 字符表示,但 html 是 html?)。我在 write 方法中尝试了不同的编码选项,但似乎没有任何效果。

编辑:这是一个最小的工作示例。获取一个输入 XML 模板文件,例如:

<?xml version='1.0' encoding='UTF-8'?>
<document>
        <title> Text to replace </title>
</document>

我们尝试像这样修改文本

import xml.etree.ElementTree as ET

tree = ET.parse('example.xml')
root = tree.getroot()
to_sub_text = "This is a test of <br/> Hershey's <sup>&$174;</sup> chocolate factory machine"
spot = root.find('title')
spot.text = to_sub_text
tree.write('example_mod.xml', encoding='UTF-8', xml_declaration=True)

这将写入文件:

<?xml version='1.0' encoding='UTF-8'?>
<document>
        <title>This is a test of &lt;br/&gt; Hershey's &lt;sup&gt;&amp;$174;&lt;/sup&gt; chocolate factory machine</title>
</document>

正如我所说,我试图复制的文档将这些 html 标签作为标签。我的问题是:

  1. 我可以修改我的代码来做到这一点吗?
  2. 是在做这个好的做法,还是保持现状更好(因此我需要与团队交谈,要求我以这种方式提供给他们)?

标签: python-3.xxmlcharacter-encodingelementtree

解决方案


spot.text = to_sub_text分配不工作。元素的text属性只包含纯文本。不能使用它来添加文本和子元素。

您可以做的是创建一个新的<title>元素对象并将其附加到根:

import xml.etree.ElementTree as ET
 
tree = ET.parse('example.xml')
root = tree.getroot()
 
# Remove the old title element
old_title = root.find('title')
root.remove(old_title)
 
# Add a new title
new_title = "<title>This is a test of <br/> Hershey's <sup>&#174;</sup> chocolate factory machine</title>"
root.append(ET.fromstring(new_title))
 
# Prettify output (requires Python 3.9) 
ET.indent(tree)
 
# Use encoding='US-ASCII' to force output of character references for non-ASCII characters
tree.write('example_mod.xml', encoding='US-ASCII', xml_declaration=True)

example_mod.xml 中的输出:

<?xml version='1.0' encoding='US-ASCII'?>
<document>
  <title>This is a test of <br /> Hershey's <sup>&#174;</sup> chocolate factory machine</title>
</document>

推荐阅读