Skip to content Skip to sidebar Skip to footer

Outputting An "unused" Xml Namespace Using Elementtree

I'm using Python 3.2's xml.etree.ElementTree, and am attempting to generate XML like this: .

Solution 1:

>>>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>

Solution 2:

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'))

yields

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

Post a Comment for "Outputting An "unused" Xml Namespace Using Elementtree"