2011-03-28 58 views
1

我的意圖是在Google App Engine中部署Web服務。我正在使用CherryPy,因爲我發現它很容易理解。Cherry Py - 在Python中以XML形式返回輸出

import sys 
sys.path.insert(0,'cherrypy.zip') 

import cherrypy 
from cherrypy import expose 

class Converter: 
    @expose 
    def index(self): 
     return "Hello World!" 

    @expose 
    def fahr_to_celc(self, degrees): 
     temp = (float(degrees) - 32) * 5/9 
     return "%.01f" % temp 

    @expose 
    def celc_to_fahr(self, degrees): 
     temp = float(degrees) * 9/5 + 32 
     return "%.01f" % temp 

cherrypy.quickstart(Converter()) 

我想知道,如何返回XML格式輸出,就像

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <answer>Hello World!</answer>  
</root> 

我在Python初學者。請幫助我。

Hariharan

回答

3

我有類似的問題。我的解決方案是使用xml elementtree。這是像

.... 
#elementtree is stored in weird places... This catches most of em 
try: 
    import xml.etree.ElementTree as ET # in python >=2.5 
except ImportError: 
    try: 
      import cElementTree as ET # effbot's C module 
     except ImportError: 
     try: 
      import elementtree.ElementTree as ET # effbot's pure Python module 
      except ImportError: 
        try: 
         import lxml.etree as ET # ElementTree API using libxml2 
        except ImportError: 
         import warnings 
         warnings.warn("could not import ElementTree " 
           "(http://effbot.org/zone/element-index.htm)") 

def build_xml_tree(answer_txt=""): 
    if not len(resources): 
     return "" 
    root = ET.Element("root") 
    answer = ET.SubElement(root, "answer") 
    answer.text = answer_txt 
    xml_string = ET.tostring(root) 
    return rxml_string 

然後調用build_xml_tree從功能

+0

非常感謝..它幫助。 – harihb 2011-03-28 15:19:57