为了清晰起见,在更多步骤中:
>>> NS = 'http://www.w3.org/2001/XMLSchema-instance'
据我所知,这是属性
noNameSpaceSchemaLocation
您想要的名称空间,而不是
TreeInventory
元素。所以:
>>> location_attribute = '{%s}noNameSpaceSchemaLocation' % NS
>>> elem = etree.Element('TreeInventory', attrib={location_attribute: 'Trees.xsd'})
>>> etree.tostring(elem, pretty_print=True)
'<TreeInventory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Trees.xsd"/>\n'
这看起来像你想要的…
当然,您也可以先创建元素,不使用属性,然后设置属性,如下所示:
>>> elem = etree.Element('TreeInventory')
>>> elem.set(location_attribute, 'Trees.xsd')
至于
nsmap
参数:我相信它只用于定义序列化时要使用的前缀。在这种情况下,不需要这样做,因为LXML知道所讨论的名称空间的常用前缀是“xsi”。如果它不是某个众所周知的名称空间,您可能会看到前缀,如“ns0”、“ns1”等,除非您指定了您喜欢的前缀。(记住:前缀不重要)