ElementTree and xsi to xmlns conversion?

Fredrik Lundh fredrik at pythonware.com
Thu May 19 03:13:11 EDT 2005


Matthew Thorley wrote:
> Why does ElementTree.parse convert my xsi to an xmlns?

because it is a namespace prefix, perhaps?

> When I do this
> from elementtree import ElementTree
>
> # Sample xml
> mgac ="""
> <mgac xmlns="http://www.chpc.utah.edu/~baites/mgacML"
>      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
>      xsi:schemaLocation="http://www.chpc.utah.edu/~baites/mgacML
> http://www.chpc.utah.edu/~baites/mgacML/mgac.xsd"><cluster
> name="Si4H"></cluster></mgac>
> """
>
> xml = ElementTree.fromstring(mgac)
> ElementTree.tostring(xml)
>
> I get this
> '<ns0:mgac ns1:schemaLocation="http://www.chpc.utah.edu/~baites/mgacML
> http://www.chpc.utah.edu/~baites/mgacML/mgac.xsd"
> xmlns:ns0="http://www.chpc.utah.edu/~baites/mgacML"
> xmlns:ns1="http://www.w3.org/2001/XMLSchema-instance"><ns0:cluster
> name="Si4H" /></ns0:mgac>'
>
> The xsi is gone and has been replaced by a new xmlns, which is also NOT
> inherited by the child elements.

the xsi is a namespace prefix, which maps to a namespace URI.  the child element
doesn't use that namespace, so there's no need to add a namespace declaration.

> ElementTree.tostring(xml.getchildren()[0])
>
> '<ns0:cluster name="Si4H"
> xmlns:ns0="http://www.chpc.utah.edu/~baites/mgacML" />'
>
> If some one could please explain where I'm off I'd really appreciate it.
> I need to use xsi: to validate the document

are you sure?  the prefix shouldn't matter; it's the namespace URI that's important.
if you're writing code that depends on the namespace prefix rather than the name-
space URI, you're not using namespaces correctly.  when it comes to namespaces,
elementtree forces you to do things the right way:

    http://www.jclark.com/xml/xmlns.htm

(unfortunately, the XML schema authors didn't understand namespaces so they
messed things up:
    http://www.w3.org/2001/tag/doc/qnameids-2002-04-30
to work around this, see oren's message about how to control the namespace/prefix
mapping.  in worst case, you can manually insert xsi:-attributes in the tree, and rely on
the fact that the default writer only modifies universal names)

</F> 






More information about the Python-list mailing list