Transforming an XML Document from its Parse Tree : XML Transform : XML PYTHON examples


PYTHON examples » XML » XML Transform »

 

Transforming an XML Document from its Parse Tree


 
import sys
from xml.dom.ext import PrettyPrint
from xml.dom import minidom

doc = minidom.parse(open(sys.argv[1]))

def walk_tree(n,func):
    while n:
        func(n)
        walk_tree(n.firstChild,func)
        n = n.nextSibling

def fix_node(n):
    if n.nodeType == n.ELEMENT_NODE:
        if n.tagName == "ingredients":
            n.tagName = "ingredientlist"
        if n.tagName == "item":
            n.tagName = "ingredient"
            attr = n.getAttribute("num")
            n.setAttribute("quantity",attr)
            n.removeAttribute("num")

walk_tree(doc,fix_node)
PrettyPrint(doc)

   
  



Leave a Comment / Note


 
Verification is used to prevent unwanted posts (spam). .


PYTHON examples

 Navioo XML
» XML Transform