首页 > 解决方案 > 具有多个命名空间的 XML 解析

问题描述

我正在尝试使用 Python 的用于 xml 解析的标准库来解析和编写 XML。

xml的格式如下:

xml = '<class:Classification xmlns:class="schema:SpeciesClassification:2.0" xmlns="http://www.w3.org/1999/xhtml" dateClassified="2019-02-11" endangeredMarking="false" caveat="false"></class:Classification>'

当我解析这个 xml 然后将它推回一个字符串时,我得到了一些奇怪的东西。都class:变成了ns0。如何保留这些标记?


from xml.etree.cElementTree import Element, SubElement, parse, tostring, fromstring

print(tostring(fromstring(xml)))
b'<ns0:Classification xmlns:ns0="schema:SpeciesClassification:2.0" caveat="false" dateClassified="2019-02-11" endangeredMarking="false" />'

我必须指定不同的解析器吗?我只是有点迷失为什么这会被丢弃。

谢谢

标签: xmlpython-3.xpython-3.6celementtree

解决方案


推荐阅读