1 import xml.dom.minidom, re
3 def osrfXMLFileToObject(filename):
4 """Turns the contents of an XML file into a Python object"""
5 doc = xml.dom.minidom.parse(filename)
6 obj = osrfXMLNodeToObject(doc.documentElement)
10 def osrfXMLStringToObject(string):
11 """Turns an XML string into a Python object"""
12 doc = xml.dom.minidom.parseString(string)
13 obj = osrfXMLNodeToObject(doc.documentElement)
17 def osrfXMLNodeToObject(xmlNode):
18 """Turns an XML node into a Python object"""
21 if xmlNode.nodeType != xmlNode.ELEMENT_NODE:
25 nodeName = xmlNode.nodeName
27 for nodeChild in xmlNode.childNodes:
28 if nodeChild.nodeType == xmlNode.ELEMENT_NODE:
29 subObj = osrfXMLNodeToObject(nodeChild);
30 __appendChildNode(obj, nodeName, nodeChild.nodeName, subObj)
33 for attr in xmlNode.attributes.values():
34 __appendChildNode(obj, nodeName, attr.name, dict([(attr.name, attr.value)]))
37 if not done and len(xmlNode.childNodes) > 0:
38 # If the node has no element children, clean up the text
39 # content and use that as the data
40 textNode = xmlNode.childNodes[0] # extract the text node
41 data = unicode(textNode.nodeValue).replace('^\s*','')
42 data = data.replace('\s*$','')
45 # the current element contains attributes and text
46 obj[nodeName]['#text'] = data
48 # the current element contains text only
54 def __appendChildNode(obj, nodeName, childName, subObj):
55 """ If a node has element children, create a new sub-object
56 for this node, attach an array for each type of child
57 and recursively collect the children data into the array(s) """
59 if not obj.has_key(nodeName):
62 if not obj[nodeName].has_key(childName):
63 # we've encountered 1 sub-node with nodeChild's name
64 if childName in subObj:
65 obj[nodeName][childName] = subObj[childName]
67 obj[nodeName][childName] = None
70 if isinstance(obj[nodeName][childName], list):
71 # we already have multiple sub-nodes with nodeChild's name
72 obj[nodeName][childName].append(subObj[childName])
75 # we already have 1 sub-node with nodeChild's name, make
76 # it a list and append the current node
77 val = obj[nodeName][childName]
78 obj[nodeName][childName] = [ val, subObj[childName] ]
81 def osrfObjectFindPath(obj, path, idx=None):
82 """Searches an object along the given path for a value to return.
84 Path separaters can be '/' or '.', '/' is tried first."""
88 if re.search('/', path):
89 parts = path.split('/')
91 parts = path.split('.')
100 if isinstance(o,list):
104 if isinstance(o,dict):