X-Git-Url: https://git.sesse.net/?a=blobdiff_plain;f=python%2Fxmltemplate.py;h=434868703e1d014c36525b0feaab72ae087dea7f;hb=HEAD;hp=6b9c50b65d2f035e45617b07f874c24d400eccf1;hpb=7d72f65df6a54392f095ebfe09bfd5ea4f1a4afd;p=xml-template diff --git a/python/xmltemplate.py b/python/xmltemplate.py index 6b9c50b..4348687 100644 --- a/python/xmltemplate.py +++ b/python/xmltemplate.py @@ -1,14 +1,21 @@ #! /usr/bin/python import re +import sys import xml.dom.minidom +if sys.version_info[0] > 2: + string = str +else: + string = basestring + + def process_file(filename, obj, clean = True): doc = xml.dom.minidom.parse(filename) process(doc, obj, clean) return doc def process(node, obj, clean = True): - if isinstance(obj, str): # overwrite + if isinstance(obj, string): # overwrite while not node.firstChild is None: node.removeChild(node.firstChild) doc = _get_document_element(node) @@ -32,13 +39,21 @@ def process(node, obj, clean = True): id = None attrs = child.attributes + attrs_to_remove = [] if not attrs is None: for i in range(attrs.length): - attr = attrs.item(0) - if attr.namespaceURI == "http://template.sesse.net/" or attr.name == "id": + attr = attrs.item(i) + if attr.namespaceURI == "http://template.sesse.net/" and attr.localName == "id": id = attr.value if clean: - child.removeAttribute(attr.name) + attrs_to_remove.append(attr.name) + if attr.name.startswith("xmlns:") and attr.value == "http://template.sesse.net/" and clean: + attrs_to_remove.append(attr.name) + + for a in attrs_to_remove: + if child.hasAttribute(a): + child.removeAttribute(a) + # check all substitutions to see if we found anything # appropriate @@ -55,7 +70,7 @@ def process(node, obj, clean = True): if not processed: process(child, obj, clean) - elif isinstance(obj, list): # repeat + elif hasattr(obj, '__iter__'): # repeat doc = _get_document_element(node) frag = doc.createElement("temporary-fragment") # ugh @@ -65,11 +80,12 @@ def process(node, obj, clean = True): frag.appendChild(child) for instance in obj: - newnode = frag.cloneNode(True) - node.appendChild(newnode) - process(newnode, instance, clean) - if clean: - _clean(newnode) + if instance is not None: + newnode = frag.cloneNode(True) + node.appendChild(newnode) + process(newnode, instance, clean) + if clean: + _clean(newnode) # remove all the tags @@ -91,8 +107,9 @@ def process(node, obj, clean = True): def alternate(tag, array, *elems): i = 0 for ref in array: - ref[tag] = elems[i % len(elems)] - i = i + 1 + if ref is not None: + ref[tag] = elems[i % len(elems)] + i = i + 1 return array