使用Python ElementTree创建不带ns0命名空间的SVG/XML文档
我正在用Python 2.7的ElementTree库创建一个SVG文档。以下是我的代码:
from xml.etree import ElementTree as etree
root = etree.XML('<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"></svg>')
root.append(etree.Element("path"))
root[0].set("d", "M1 1 L2 2 Z")
print etree.tostring(root, encoding='iso-8859-1')
这段代码生成了以下输出:
<?xml version='1.0' encoding='iso-8859-1'?>
<ns0:svg xmlns:ns0="http://www.w3.org/2000/svg" height="100%" version="1.1" width="100%"><path d="M1 1 L2 2 Z" /></ns0:svg>
但是这个输出并不能被当作有效的SVG文件解析。请问我该如何去掉ns0这个命名空间呢?
2 个回答
0
这是我用lxml库来处理的方式。
from lxml import etree
svg_tree = etree.fromstring(svg_str, parser=etree.XMLParser())
etree.tostring(svg_tree)
我使用了这里的示例代码: lxml-removing-xml-tags-when-parsing
56
我刚刚搞明白了这个问题,但我不能删除这个提问,所以就把它放在这里:
etree.register_namespace("","http://www.w3.org/2000/svg")
我觉得这个只在Python 2.7及之后的版本有效。