温馨提示×

Python怎么在XML实体中替换特殊字符

小亿
85
2024-04-02 14:03:56
栏目: 编程语言

在 Python 中,可以使用 html.entities 模块来替换 XML 实体中的特殊字符。下面是一个示例代码,演示了如何将特殊字符替换为对应的 XML 实体:

import html
import xml.etree.ElementTree as ET

# 定义一个包含特殊字符的字符串
special_chars = "<foo>bar</foo>"

# 将特殊字符替换为对应的 XML 实体
escaped_chars = html.escape(special_chars)

# 创建一个 XML 元素
root = ET.Element("root")
root.text = escaped_chars

# 输出 XML
xml_str = ET.tostring(root, encoding='unicode')
print(xml_str)

在这个例子中,我们首先使用 html.escape() 函数将包含特殊字符的字符串 "<foo>bar</foo>" 转换为对应的 XML 实体 <foo>bar</foo>。然后我们创建一个包含该转义后字符串的 XML 元素,并将其输出为字符串形式。

运行上述代码后,将会输出以下结果:

<root><foo>bar</foo></root>

0