如何在Python中检索xml标记的属性?

Moa*_*ghi 2 python xml tags

我正在寻找一种在python中向xml标签添加属性的方法.或者,例如,要创建具有新属性的新标记,我有以下xml文件:

<types name='character' shortName='chrs'>
....
...

</types>
Run Code Online (Sandbox Code Playgroud)

我想添加一个属性,使它看起来像这样:

<types name='character' shortName='chrs' fullName='MayaCharacters'>
....
...
</types>
Run Code Online (Sandbox Code Playgroud)

我怎么用python做到这一点?顺便说说.我请用python和minidom来帮忙.提前致谢

And*_*Dog 5

您可以使用相应对象的attributes属性Node.

例如:

from xml.dom.minidom import parseString
documentNode = parseString("<types name='character' shortName='chrs'></types>")
typesNode = documentNode.firstChild

# Getting an attribute
print typesNode.attributes["name"].value # will print "character"

# Setting an attribute
typesNode.attributes["mynewattribute"] = u"mynewvalue"
print documentNode.toprettyxml()
Run Code Online (Sandbox Code Playgroud)

最后一个print语句将输出此XML文档:

<?xml version="1.0" ?>
<types mynewattribute="mynewvalue" name="character" shortName="chrs"/>
Run Code Online (Sandbox Code Playgroud)