Python lxml tostring 不打印 nsmap

Python lxml tostring not print nsmap

我在 Doxygen XML 解析器中工作。我的问题其实很简单,我需要使用 LXML 的 tostring 来获取 XML 元素的原始内容。

我在 ETree 上使用它,但我切换到 LMXL,所以我得到 strip_tags

假设我有这个 XML 文件:

<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.8.16">
  <child2/>
  <child3/>
</root>

我这样做:

tree = ET.parse('new1.xml')
root = tree.getroot()
child3 = root.find("./child3")

objectify.deannotate(child3, cleanup_namespaces=True, xsi=True, pytype=True)
etree.cleanup_namespaces(child3)
child3.nsmap.clear()
etree.strip_attributes(child3, 'nsmap') 

print(ET.tostring(child3, encoding='unicode', pretty_print=True))

这是我得到的:

<child3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>

这就是我想要的:

<child3/>

是否有一个选项可以将字符串 NOT 打印 nsmap?

我试过了:

如果我尝试

root.nsmap = None

我遇到异常:

AttributeError: attribute 'nsmap' of 'lxml.etree._Element' objects is not writable

我正在使用 Python 3.7 64 位和 Windows 10.

谢谢。

在 XML 文档中,正在使用 http://www.w3.org/2001/XMLSchema 命名空间。 xsi:noNamespaceSchemaLocation 属性绑定到该命名空间。

为了获得想要的输出,您必须 1) 删除 xsi:noNamespaceSchemaLocation 属性和 2) 删除命名空间的声明。

from lxml import etree

tree = etree.parse('new1.xml')
root = tree.getroot()

# Remove the xsi:noNamespaceSchemaLocation attribute
del root.attrib["{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation"]

# Remove the declaration for the now unused namespace. Must be done on the root element
etree.cleanup_namespaces(root)

child3 = root.find("./child3")

# Print child3
print(etree.tostring(child3, encoding='unicode', pretty_print=True))

# Print the whole document
print(etree.tostring(root, encoding='unicode', pretty_print=True))

输出:

<child3/>


<root version="1.8.16">
  <child2/>
  <child3/>
</root>