2

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

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

The format is out of my control (it's XNA). Notice that the data XML namespace is never actually used to qualify elements or attributes, but rather to qualify attribute values to XNA. My code looks like this:

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

However, the output looks like (pretty-printed by me):

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

How can I get the data XML namespace included in the output?

me--
  • 1,978
  • 1
  • 22
  • 42

2 Answers2

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>
root
  • 76,608
  • 25
  • 108
  • 120
  • Thanks, but I get: `AttributeError: 'Element' object has no attribute 'nsmap'`, nor is `nsmap` mentioned [here](http://docs.python.org/library/xml.etree.elementtree.html) – me-- Oct 20 '12 at 12:22
  • @unutbu: correct, but I am not and cannot - it's not available in my Python environment. – me-- Oct 20 '12 at 12:32
  • @unutbu is right, I am using lxml, i only briefly looked at your code and presumed that so were you. Hope you will find an answer for xml.etree. but i am afraid, it might be a problematic. – root Oct 20 '12 at 12:35
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'))

yields

<data:XnaContent xmlns:data="ModelData">
      <Asset Type="data:MyData" />
      <Asset Type="data:MyData" />
    </data:XnaContent>
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Thanks, but that's not what I want. You've put `XnaContent` in the `data` namespace, but it isn't supposed to be. – me-- Oct 20 '12 at 13:18