cx_Oracle and python to get query results as XML?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • caneflo
    New Member
    • Sep 2010
    • 2

    cx_Oracle and python to get query results as XML?

    I am using cx_Oracle and python 2.6 to get query results from oracle 10g database. Is there way using cx_Oracle or some other program to easily get resuls as XML. I presently take the python data structure and convert it json for use with javascripts. I now need to move to XML.
    Any ideas or suggestions?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    The method of building your XML document would depend on your data structure and whether you want to save your data as text nodes, attributes, or a combination of the two. Following are examples that create XML documents from a simple dictionary.
    Code:
    '''
    Dictionary to XML
    The dictionary keys are XML tags and the values are text node values.
    '''
    
    from xml.dom import minidom
    
    def createTextNodes(dd):
        xmldoc = minidom.Document()
        xmldoc.appendChild(xmldoc.createComment("This is a comment"))
    
        root = xmldoc.createElement('root')
        xmldoc.appendChild(root)
    
        for key in dd:
            a = xmldoc.createElement(key)
            b = xmldoc.createTextNode(str(dd[key]))
            root.appendChild(a)
            a.appendChild(b)
            
        return xmldoc
    
    def createAttrs(dd):
        xmldoc = minidom.Document()
        xmldoc.appendChild(xmldoc.createComment("This is a comment"))
    
        root = xmldoc.createElement('root')
        xmldoc.appendChild(root)
        
        dataNode = xmldoc.createElement('data')
        root.appendChild(dataNode)
    
        for key in dd:
            dataNode.setAttribute(key, str(dd[key]))
            
        return xmldoc
    
    dd = {'code_version': 4.02, 'version': 1}
    
    x1 = createTextNodes(dd)
    print x1.toprettyxml()
    
    x2 = createAttrs(dd)
    print x2.toprettyxml()
    The results:
    Code:
    >>> <?xml version="1.0" ?>
    <!--This is a comment-->
    <root>
    	<code_version>
    		4.02
    	</code_version>
    	<version>
    		1
    	</version>
    </root>
    
    <?xml version="1.0" ?>
    <!--This is a comment-->
    <root>
    	<data code_version="4.02" version="1"/>
    </root>
    
    >>>

    Comment

    • caneflo
      New Member
      • Sep 2010
      • 2

      #3
      Sweet! I will give this a go and let you how it turns out. I like how you incorporated the <root> and comment. I will use that to incorporate a time stamp to my xml output.

      Comment

      Working...