如何保持html标签时,写一个ElementTree树到磁盘?



我正试图使用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. 是在做这种良好的做法,还是最好让它保持目前的状态(因此我需要与团队交谈,要求我以这种方式提供给他们)?

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>