我正在向 xml 文件中添加元素。
文档的根目录如下
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Run Code Online (Sandbox Code Playgroud)
和要添加的元素看起来像
<Element xsi:type="some type">
<Sub1>Some text</Sub1>
<Sub2>More text</Sub2>
...
</Element>
Run Code Online (Sandbox Code Playgroud)
我试图找到一种方法让 lxml 在我的 Element 的属性前写上“xsi:”。这个 xml 文件被一个程序使用,我无权访问它的源代码。我在其他一些问题中阅读了如何通过声明 xml 根的 nsmap 来实现,然后再次在 child 的属性中,我尝试过但它没有用。到目前为止我有(那是行不通的,输出文件不包含 xsi 前缀):
element = SubElement(_parent=parent,
_tag='some tag',
attrib={'{%s}type' % XSI: 'some type'}
nsmap={'xsi': XSI}) # Where XSI = namespace address
Run Code Online (Sandbox Code Playgroud)
在我解析的 xml 文件中正确声明了命名空间,所以我不知道为什么这不起作用。我得到的输出是如上所示的元素,没有 'xsi:' 前缀,全部在一行中:
<Element type="some type"><Sub1>Some text</Sub1><Sub2>More text</Sub2>...</Element>
Run Code Online (Sandbox Code Playgroud)
如果有人也可以指出为什么在这一行
self.tree.write(self.filename, pretty_print=True, encoding='utf-8')
Run Code Online (Sandbox Code Playgroud)
'pretty_print' 选项不起作用(全部打印在一行中),将不胜感激。
from math import floor
from lxml import etree
from lxml.etree import SubElement
def …Run Code Online (Sandbox Code Playgroud)