Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

python 3.x - How to add xmi:version="2.0" attribute to an element

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...