使用ElementTree输出“未使用的”XML命名空间

时间:2012-10-20 11:21:41

标签: python xml elementtree

我正在使用Python 3.2的xml.etree.ElementTree,我正在尝试生成这样的XML:

<XnaContent xmlns:data="Model.Data">
    <Asset Type="data:MyData">
        ...

格式不受我的控制(它是XNA)。请注意,data XML命名空间从未实际用于限定元素或属性,而是用于将属性值限定为XNA。我的代码如下所示:

root = Element('XnaContent')
ET.register_namespace('data', 'Model.Data') 
asset = SubElement(root, 'Asset', {"Type": "data:MyData"})

然而,输出看起来像(由我精心打印):

<XnaContent>
    <Asset Type="data:MyData">
        ...
    </Asset>
</XnaContent>

如何在输出中包含data XML命名空间?

2 个答案:

答案 0 :(得分:2)

>>>print ET.tostring(doc, pretty_print=True)
<XnaContent>
  <Asset Type="data:MyData"/>
  <Asset Type="data:MyData"/>
</XnaContent>
>>> tree=ET.ElementTree(doc)
>>> root=tree.getroot()
>>> nsmap=root.nsmap
>>> nsmap['data']="ModelData"
>>> new_root = ET.Element(root.tag, nsmap=nsmap)
>>> print ET.tostring(new_root, pretty_print=True)
<XnaContent xmlns:data="ModelData"/>
>>> new_root[:] = root[:]
>>> print ET.tostring(new_root, pretty_print=True)
<XnaContent xmlns:data="ModelData">
  <Asset Type="data:MyData"/>
  <Asset Type="data:MyData"/>
</XnaContent>

答案 1 :(得分:1)

import xml.etree.ElementTree as ET
content = '''
<XnaContent>
  <Asset Type="data:MyData"/>
  <Asset Type="data:MyData"/>
</XnaContent>'''
doc = ET.fromstring(content)
ET.register_namespace('data','ModelData')
tree = ET.ElementTree(doc)
root = tree.getroot()
root.tag = '{ModelData}XnaContent'
print(ET.tostring(root, method = 'xml'))

产量

<data:XnaContent xmlns:data="ModelData">
      <Asset Type="data:MyData" />
      <Asset Type="data:MyData" />
    </data:XnaContent>