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:
30 # If a node has element children, create a new sub-object
31 # for this node, attach an array for each type of child
32 # and recursively collect the children data into the array(s)
34 if not obj.has_key(nodeName):
37 sub_obj = osrfXMLNodeToObject(nodeChild);
39 if not obj[nodeName].has_key(nodeChild.nodeName):
40 # we've encountered 1 sub-node with nodeChild's name
41 obj[nodeName][nodeChild.nodeName] = sub_obj[nodeChild.nodeName]
44 if isinstance(obj[nodeName][nodeChild.nodeName], list):
45 # we already have multiple sub-nodes with nodeChild's name
46 obj[nodeName][nodeChild.nodeName].append(sub_obj[nodeChild.nodeName])
49 # we already have 1 sub-node with nodeChild's name, make
50 # it a list and append the current node
51 val = obj[nodeName][nodeChild.nodeName]
52 obj[nodeName][nodeChild.nodeName] = [ val, sub_obj[nodeChild.nodeName] ]
57 # If the node has no element children, clean up the text content
58 # and use that as the data
59 xmlNode = xmlNode.childNodes[0] # extract the text node
60 data = re.compile('^\s*').sub('', unicode(xmlNode.nodeValue))
61 data = re.compile('\s*$').sub('', data)
68 def osrfObjectFindPath(obj, path, idx=None):
69 """Searches an object along the given path for a value to return.
71 Path separaters can be '/' or '.', '/' is tried first."""
75 if re.search('/', path):
76 parts = path.split('/')
78 parts = path.split('.')
87 if isinstance(o,list):
91 if isinstance(o,dict):