开发者

How to retrieve attributes of xml tag in Python?

I'm looking for a way to add attributes to xml tags in python. Or to create a new tag开发者_运维技巧 with a new attributes for example, I have the following xml file:

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

</types>

and i want to add an attribute to make it look like this:

<types name='character' shortName='chrs' fullName='MayaCharacters'>
....
...
</types>

how do I do that with python? by the way. I use python and minidom for this please help. thanks in advance


You can use the attributes property of the respective Node object.

For example:

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

The last print statement will output this XML document:

<?xml version="1.0" ?>
<types mynewattribute="mynewvalue" name="character" shortName="chrs"/>


I learned xml parsing in python from this great article. It has an attribute section, which cant be linked to, but just search for "Attributes" on that page and you'll find it, that holds the information you need.

But in short (snippet stolen from said page):

>>> building_element.setAttributeNS("http://www.boddie.org.uk/paul/business", "business:name", "Ivory Tower")
>>> building_element.getAttributeNS("http://www.boddie.org.uk/paul/business", "name")
'Ivory Tower'

You probably want to skip the handling of namespaces, to make the code cleaner, unless you need them.


It would seem that you just call setAttribute for the parsed dom objects.

http://developer.taboca.com/cases/en/creating_a_new_xml_document_with_python/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜