By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,199 Members | 1,064 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,199 IT Pros & Developers. It's quick & easy.

cx_Oracle and python to get query results as XML?

P: 2
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?
Sep 8 '10 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
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.
Expand|Select|Wrap|Line Numbers
  1. '''
  2. Dictionary to XML
  3. The dictionary keys are XML tags and the values are text node values.
  4. '''
  5.  
  6. from xml.dom import minidom
  7.  
  8. def createTextNodes(dd):
  9.     xmldoc = minidom.Document()
  10.     xmldoc.appendChild(xmldoc.createComment("This is a comment"))
  11.  
  12.     root = xmldoc.createElement('root')
  13.     xmldoc.appendChild(root)
  14.  
  15.     for key in dd:
  16.         a = xmldoc.createElement(key)
  17.         b = xmldoc.createTextNode(str(dd[key]))
  18.         root.appendChild(a)
  19.         a.appendChild(b)
  20.  
  21.     return xmldoc
  22.  
  23. def createAttrs(dd):
  24.     xmldoc = minidom.Document()
  25.     xmldoc.appendChild(xmldoc.createComment("This is a comment"))
  26.  
  27.     root = xmldoc.createElement('root')
  28.     xmldoc.appendChild(root)
  29.  
  30.     dataNode = xmldoc.createElement('data')
  31.     root.appendChild(dataNode)
  32.  
  33.     for key in dd:
  34.         dataNode.setAttribute(key, str(dd[key]))
  35.  
  36.     return xmldoc
  37.  
  38. dd = {'code_version': 4.02, 'version': 1}
  39.  
  40. x1 = createTextNodes(dd)
  41. print x1.toprettyxml()
  42.  
  43. x2 = createAttrs(dd)
  44. print x2.toprettyxml()
The results:
Expand|Select|Wrap|Line Numbers
  1. >>> <?xml version="1.0" ?>
  2. <!--This is a comment-->
  3. <root>
  4.     <code_version>
  5.         4.02
  6.     </code_version>
  7.     <version>
  8.         1
  9.     </version>
  10. </root>
  11.  
  12. <?xml version="1.0" ?>
  13. <!--This is a comment-->
  14. <root>
  15.     <data code_version="4.02" version="1"/>
  16. </root>
  17.  
  18. >>> 
Sep 8 '10 #2

P: 2
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.
Sep 8 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.