如何添加xmi:version ="2.0"元素的属性 [英] How to add xmi:version="2.0" attribute to an element

查看:61
本文介绍了如何添加xmi:version ="2.0"元素的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个xml文件.我已经完成了创建根元素的工作,并且能够定义xml声明.但是我需要创建一个花药标签,看起来像

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>

我已经添加了xmlns URI,但是无法获取xmi:version ="2.0".

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

我对XML不熟悉,所以感到困惑,请阅读有关名称空间及其全部内容的知识,而不能完全理解它.有人可以教我如何做或分享相关的网络链接吗?那会很有帮助.因为我在Internet上发现了大多数XML解析内容,但在XML生成资源上却很少.

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

推荐答案

创建命名空间元素和属性的好方法是使用

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

结果:

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

register_namespace()确保序列化XML文档时使用 xmi 前缀(不是默认的 ns0 ).

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

这篇关于如何添加xmi:version ="2.0"元素的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆