Outputting an "unused" XML namespace using ElementTree
Asked Answered
F

2

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?

Fencesitter answered 20/10, 2012 at 11:21 Comment(0)
A
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>
Assagai answered 20/10, 2012 at 12:12 Comment(3)
Thanks, but I get: AttributeError: 'Element' object has no attribute 'nsmap', nor is nsmap mentioned hereFencesitter
@unutbu: correct, but I am not and cannot - it's not available in my Python environment.Fencesitter
@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.Assagai
C
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>
Crockery answered 20/10, 2012 at 13:5 Comment(1)
Thanks, but that's not what I want. You've put XnaContent in the data namespace, but it isn't supposed to be.Fencesitter

© 2022 - 2024 — McMap. All rights reserved.