python-3.x - 将 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 标签将被转换为<br>
或商标符号(® 的东西)将显示为实际符号。有没有办法对我的文本进行编码以获得上述输出(其中商标由 ® 字符表示,但 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 <br/> Hershey's <sup>&$174;</sup> chocolate factory machine</title>
</document>
正如我所说,我试图复制的文档将这些 html 标签作为标签。我的问题是:
- 我可以修改我的代码来做到这一点吗?
- 是在做这个好的做法,还是保持现状更好(因此我需要与团队交谈,要求我以这种方式提供给他们)?
解决方案
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>®</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>®</sup> chocolate factory machine</title>
</document>
推荐阅读
- sql - POSTGRES SQL Left Join 仅返回右表上最大的 UID?
- android - Android:如何以编程方式禁用屏幕截图并显示其小吃栏
- javascript - JavaScript 代理使用
- r - 按名称分组,如何将没有值的名称设置为 0?
- python - Pyplot Histogram - 从自动 bin 中获取准确的 x 值
- javascript - 为什么 x=0 等价于 x=''
- amazon-web-services - 无法让两个账户之间的 Amazon S3 跨区域复制工作
- apache-spark - 如果通过 :paste 粘贴代码,则 Spark 捕获的变量为 null
- javascript - 通过道具 React 将 WS 连接传递给孩子
- excel - 如何将多个 ID 汇总为单个类别?