How to add xmi:version="2.0" attribute to an element
Asked Answered
A

1

1

I am creating a xml file. i am done with the root element creation and i am able to define xml declaration. But i need to create anther tag, which looks like

<?xml version="1.0" encoding="UTF-8"?>
<xmi:XMI xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:TalendProperties="http://www.talend.org/properties">
# i am unable to replicate the above

### some subelements..
</xmi:XMI>

i am done with adding xmlns URIs, but unable to get the xmi:version="2.0".

I am not familiar with XML, so getting confused, read about namespace and all, not quite getting it. Can somebody show me how to do that or share a related weblink. That woul dbe great help. Because i found mostly the XML parsing stuff on internet but very few resource on XML generaton.

  xmlns_uris_dict = {'xmi':'http://..', 'subprocess':'http://xyz...'}
  root = ET.Element("talendfile:ProcessType")
  ET.register_namespace('xmi', 'version="2.0"') # This part gives a wrong presentation.
  # i am able to add URIs here
  for prefix, uri in xmlns_uris_dict.items():
    root.attrib['xmlns:' + prefix] = uri
Athelstan answered 31/10, 2019 at 11:20 Comment(0)
V
3

A good way to create namespaced elements and attributes is to use QName.

import xml.etree.ElementTree as ET

NS = "http://www.omg.org/XMI"
ET.register_namespace("xmi", NS)

# Create xmi:XMI element
root = ET.Element(ET.QName(NS, "XMI"))

# Add xmi:version attribute
root.set(ET.QName(NS, "version"), "2.0")

print(ET.tostring(root).decode())

Result:

<xmi:XMI xmlns:xmi="http://www.omg.org/XMI" xmi:version="2.0" />

register_namespace() ensures that the xmi prefix (not the default ns0) is used when serializing the XML document.

Vallee answered 3/11, 2019 at 8:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.