Add attribute using pyxml

Robert Boyd robert.h.boyd at gmail.com
Tue Nov 1 14:33:19 EST 2005


On 1 Nov 2005 11:09:10 -0800, PyPK <superprad at gmail.com> wrote:
>
> How do I add a new attribute to the existing xml Document tree???
>

Add an attribute of an element, or add a new element?

I hope I've understood your question correctly...this demonstrates both
adding a brand new element (tag) and an attribute for it.

from xml.dom.ext.reader.Sax2 import FromXmlStream

doc = FromXmlStream(stream) # or FromXmlStream(open(name_of_file))
NewElement = doc.createElement('NewElement')
NewElement.setAttribute('attribute_name', 'attribute_value')
doc.documentElement.appendChild(NewElement)

You'll wind up with <NewElement attribute_name='attribute_value' />
You may need to use getElementsByTagName or other means to find the exact
node to place your new element if you aren't putting it directly under the
root element.

To save into the original xml file, I create a filehandle to the file, then
PrettyPrint(doc, fh).

DISLAIMER: I just learned this last week, so if anything is wrong or could
be improved, the list is welcome to correct me ;)

Rob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20051101/f1338607/attachment.html>


More information about the Python-list mailing list