将'xml:space'设置为'保留'Python lxml

Saa*_*mer 7 python xml svg lxml

我在SVG文件中有一个文本元素,我正在使用它生成lxml.我想保留这个元素中的空格.我创建文本元素,然后尝试.set()xml:spacepreserve,但没有我尝试似乎工作.我可能在概念上遗漏了一些东西.有任何想法吗?

mzj*_*zjn 7

您可以通过显式指定与特殊xml:前缀关联的名称空间URI来实现(请参阅http://www.w3.org/XML/1998/namespace).

from lxml import etree

root = etree.Element("root")
root.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")

print etree.tostring(root)
Run Code Online (Sandbox Code Playgroud)

输出:

<root xml:space="preserve"/>    
Run Code Online (Sandbox Code Playgroud)