Python独占XML标准化 (xml-exc-c14n)

5 投票
2 回答
7796 浏览
提问于 2025-04-18 02:00

在Python中,我需要对一个XML字符串进行标准化处理(也叫c14n)。

我可以使用哪个模块或包来实现这个呢?我该怎么做呢?

(我希望使用Python 2.7自带的模块,不想额外安装其他东西。)

参考链接:http://www.w3.org/TR/xml-exc-c14n/

2 个回答

0

现在在Python 3中,你可以这样写你的代码:

import lxml.etree as ET

et = ET.parse('your_xml_file_that_you_want_to_canonicalize.xml')
et.write_c14n("your_result_will_be_in_this_file.xml")
9

来自 http://www.decalage.info/en/python/lxml-c14n

lxml 提供了一种非常简单的方法来在 Python 中进行 C14N 操作。

下面是一个使用 lxml 2.1 执行 C14N 的示例:

import lxml.etree as ET
et = ET.parse('file.xml')
output = StringIO.StringIO()
et.write_c14n(output)
print output.getvalue()

来自 lxml 文档:

write_c14n(self, file, exclusive=False, with_comments=True, compression=0, inclusive_ns_prefixes=None)

这是文档的 C14N 写入方法。它总是使用 UTF-8 编码。

<..>

还有 libxml2:

XML C14N 版本 1.0 提供了两个选项,从而产生四种可能性(详细信息见 http://www.w3.org/TR/xml-c14nhttp://www.w3.org/TR/xml-exc-c14n/):

  • 包含或不包含的 C14N
  • 是否带有注释

libxml2 在其 C14N API 中提供了这些选项的访问:http://xmlsoft.org/html/libxml-c14n.html

不过,使用这两个库时要注意检查版本变化。

撰写回答