2

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

3 Answers 3

5

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"/>
Sign up to request clarification or add additional context in comments.

1 Comment

+1 i like your way in simplifying things . dude you should start writing books !
1

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.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.