[XML-SIG] Namespace prefix being changed while saving file.

Fredrik Lundh fredrik at pythonware.com
Tue Feb 28 08:31:19 CET 2006


Ajay Abhyankar wrote:

> I was trying cElementTree for reading and updating an xml file. I am
> using iterparse to parse and make relevant changes to the xml as required.
> Everything works very fine till I use a valid xml namespace in xml file.
> It is not giving any problems in manipulation of file content, but only
> changes the namespace prefix on its own to something like "ns0" and
> retains the original URL, when the file is written back after updates.
> Can the namespace prefix be retained after manipultion? Am I doing
> something wrong or have I missed out on something.
> Please help to understand and solve the problem.

the standard ET parser throws away the prefix, and the standard
serializer generates new prefixes on the fly.

for many applications, this is not a problem -- it's the namespace
URL that matters in XML, not the prefix.

if you want to preserve namespaces under stock ET, your best bet
is to use iterparse's namespace events to collect prefix information,
and either update the _namespace_map dictionary:

    from elementtree import ElementTree

    # undocumented, guaranteed to be supported in all 1.2 releases
    ElementTree._namespace_map[url] = prefix
    ElementTree._namespace_map[url] = prefix
    ...
    ... the serializer now maps {url}foo to prefix:foo, for all url/prefix
    ... pairs in the namespace map
    ...

or use a custom serializer (or a postprocessing step).

hope this helps!

</F>





More information about the XML-SIG mailing list