Python:lxml.etree.tostring(with_comments = False)

Jel*_*Cat 5 python xml xml-serialization

我调用以下命令并获得以下错误:

>>>lxml.etree.tostring([tree].getroot(), with_comments=False)
ValueError: Can only discard comments in C14N serialisation
Run Code Online (Sandbox Code Playgroud)

我不知道C14N是什么,但我很感激解释我如何实现它并运行上述命令with_comments=False.(是的,我知道我可以使用正则表达式删除注释.请不要提供正则表达式作为解决方案.)

背景:我想通过http连接传输我的xml文档.我正在使用lxml Python库.我正在运行Python 2.7.1

Tit*_*usz 8

您可以在解析时删除注释:

parser = etree.XMLParser(remove_comments=True)
tree = etree.parse(xmlfile, parser=parser)
Run Code Online (Sandbox Code Playgroud)

或者当使用objectify时(花了我一段时间才发现这个):

parser = objectify.makeparser(remove_comments=True)
tree = objectify.parse(xmlfile, parser=parser)
Run Code Online (Sandbox Code Playgroud)


Dae*_*yth 3

lxml.etree.tostring文档说:

Exclusive 和 with_comments 参数仅与 C14N 输出一起使用,它们分别请求独占和未注释的 C14N 序列化。

该参数仅在使用时有效method='c14n'。你可以省略它,据我所知,它不会包含评论。即使确实如此,接收端的 xml 解析器也应该忽略它们,所以除非存在带宽问题或者您有特定的问题,否则我不会担心它。