XML and namespaces

Paul Boddie paul at boddie.org.uk
Tue Dec 6 18:04:13 EST 2005


Alan Kennedy wrote:
> Don't confuse libxml2dom with libxml2.

Well, quite, but perhaps you can explain what I'm doing wrong with this
low-level version of the previously specified code:

import libxml2mod
document = libxml2mod.xmlNewDoc(None)
element = libxml2mod.xmlNewChild(document, None, "href", None)
print libxml2mod.serializeNode(document, None, 1)

This prints the following:

<?xml version="1.0"?>
<href/>

Extending the above code...

ns = libxml2mod.xmlNewNs(element, "DAV:", None)
print libxml2mod.serializeNode(document, None, 1)

This prints the following:

<?xml version="1.0"?>
<href xmlns="DAV:"/>

Note that libxml2mod is as close to the libxml2 C API as you can get in
Python. As far as I can tell, by using that module, you're effectively
driving the C API almost directly. Note also that libxml2mod is nothing
to do with what I've written myself - I'm just using it here, just as
libxml2dom does.

Now, in the first part of the code, we didn't specify a namespace on
the element at all, but in the second part we chose to set a namespace
on the element with a null prefix. As you can see, we get the xmlns
attribute as soon as the namespace is introduced. It is difficult to
say whether this usage of the API is correct or not, judging from the
Web site's material [1], so I'd be happy if someone could point out
improvements or corrections.

Paul

[1] http://xmlsoft.org/




More information about the Python-list mailing list