使用Python ElementTree创建没有ns0名称空间的SVG / XML文档[duplicate]

时间:2022-11-20 18:27:50

This question already has an answer here:

这个问题已经有了答案:

I'm building an SVG document with ElementTree in Python 2.7. Here is the code:

我正在用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')

This generates the output:

这个生成的输出:

<?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>

This does not parse as valid SVG. How can I remove the ns0 namespace?

这不能作为有效的SVG进行解析。如何删除ns0命名空间?

2 个解决方案

#1


45  

I just figured it out and I can't delete the question so here it is:

我刚刚算出来了,我不能删掉这个问题,这里是

etree.register_namespace("","http://www.w3.org/2000/svg")

I think this only works as of Python 2.7 though.

我认为这只适用于Python 2.7。

#2


0  

Here's how I do it with lxml.

下面是我使用lxml的方法。

from lxml import etree
svg_tree = etree.fromstring(svg_str, parser=etree.XMLParser())
etree.tostring(svg_tree)

Used sample code from here: lxml-removing-xml-tags-when-parsing

这里使用的示例代码:lxml-removing-xml-tag -when- parser

#1


45  

I just figured it out and I can't delete the question so here it is:

我刚刚算出来了,我不能删掉这个问题,这里是

etree.register_namespace("","http://www.w3.org/2000/svg")

I think this only works as of Python 2.7 though.

我认为这只适用于Python 2.7。

#2


0  

Here's how I do it with lxml.

下面是我使用lxml的方法。

from lxml import etree
svg_tree = etree.fromstring(svg_str, parser=etree.XMLParser())
etree.tostring(svg_tree)

Used sample code from here: lxml-removing-xml-tags-when-parsing

这里使用的示例代码:lxml-removing-xml-tag -when- parser