【问题标题】:How to keep xml namespace without prefix, while generating XML using lxml?如何在使用 lxml 生成 XML 时保持没有前缀的 xml 命名空间?
【发布时间】:2021-08-05 20:20:06
【问题描述】:

我正在尝试创建简单的 SVG (XML) 文件,如下所示:

root = etree.Element('{http://www.w3.org/2000/svg}svg')
root.append(element) # element is a <path> element extracted from another SVG file
print(etree.tostring(root).decode())

但这给出的输出如下:

<ns0:svg xmlns:ns0="http://www.w3.org/2000/svg"><ns0:path ...></ns0:path></ns0:svg>

这个输出几乎是正确的,但我如何摆脱它似乎随机添加的ns0: 命名空间?预期的输出是:

<svg xmlns="http://www.w3.org/2000/svg"><path ...></path></svg>

我尝试如下使用nsmap,但这会引发ValueError: Invalid namespace prefix ''

root = etree.Element('{http://www.w3.org/2000/svg}svg', nsmap={'': 'http://www.w3.org/2000/svg'})
# ...

This answer 接近了,但它删除了命名空间前缀我并不真正想要的命名空间 - 我想删除命名空间 prefix,但是保留命名空间(因为没有命名空间它就不是有效的 SVG)。

【问题讨论】:

    标签: python python-3.x xml xml-parsing lxml


    【解决方案1】:

    你已经接近了。在nsmap= 中,而不是'',使用None

    root = etree.Element('{http://www.w3.org/2000/svg}svg', nsmap={None: 'http://www.w3.org/2000/svg'})
    root.append(element) # element is a <path> element extracted from another SVG file
    print(etree.tostring(root).decode())
    

    这将保留命名空间,但不会添加任何命名空间前缀(即ns0)。

    【讨论】:

      猜你喜欢
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2022-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多