On Mon, Mar 29, 2010 at 2:31 AM, Tyler Erickson <[email protected]> wrote:
> Thanks for the ideas, which led me to
> http://effbot.org/zone/element-namespaces.htm . This page notes that the
> standard serializer passes through element names that use the prefix:tag
> notation.  So I think a good approach will be to write elements with the
> prefix:tag notation, then iterate through the tree to find out what prefixes
> I have used, and then set the appropriate namespaces on the root element of
> the tree.
>

I had the same issue, except it was a requirement because we were
using ~8 namespaces and it got heller-confusing to look at a document
without sane prefixes... I did it a hack way. I doubt this would work
for really big docs, and performance will suck :)

HTH,

Rob :)

        ... root is the root element of my generated tree ...
        namespaces = set()
        for e in root.iter():
            for ns in e.nsmap.values():
                namespaces.add(ns)
        if len(namespaces):
            # build up useful prefixes...
            nsmap = build_ns_map(namespaces)
            # build a new root element with a different nsmap
            new_root = etree.Element(root.tag, attrib=root.attrib, nsmap=nsmap)
            new_root.text=root.text
            new_root.tail=root.tail
            for c in root:
                new_root.append(c)
            root = new_root

       tree = etree.ElementTree(root)
       tree.write(output_file, encoding='utf8', pretty_print=pretty)

    def build_ns_map(namespaces):
        nsmap = {}

        for ns in namespaces:
            # build_ns_prefix() gets or creates a sensible prefix for
a given namespace URL
            prefix = build_ns_prefix(ns)
            # having a non-populated prefix map is fine, etree will fill it in
            # with ns# etc
            if prefix and (prefix not in nsmap):
                nsmap[prefix] = ns
        return nsmap

To unsubscribe from this group, send email to 
python-gis-sig+unsubscribegooglegroups.com or reply to this email with the 
words "REMOVE ME" as the subject.

Reply via email to