社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  问与答

新手解析xml报错,找不出原因

1160974245 • 10 年前 • 4155 次点击  

python2.7.3 django1.7 代码如下:使用hello函数可以正常处理text消息,奇怪的是hello报文报错(no element found: line 1, column 0)下附hello报文 谢谢,

def handRequest(request):
    if request.method == 'GET':
        response = HttpResponse(checkSignature(request))
        return response
    elif request.method == 'POST':

        res = hello(request)
        return HttpResponse(res)
    else:
        return None

def textReply(to,fromuser,createtime,content):
      text ='''<xml>
              <tousername><![CDATA[%s]]></tousername>
              <fromusername><![CDATA[%s]]></fromusername>
              <createtime>%s</createtime>
              <msgtype><![CDATA[text]]></msgtype>
              <content><![CDATA[%s]]></content>
            </xml>'''
      return text % (to,fromuser,createtime,content)



def hello(request):
        xmlstr = smart_str(request.body)

        xmldoc = ET.fromstring(xmlstr)
        to = xmldoc.find('tousername').text
        fromuser = xmldoc.find('fromusername').text
        createtime = xmldoc.find('createtime').text
        #content = xmldoc.find('content').text
        return textReply(fromuser,to,createtime,time.strftime("签到成功/n%H:%M",time.localtime(float(createtime))))





def parsexml(xmlstr):
        msg = {}
        if xmlstr.tag == 'xml':
            for child in xmlstr:
                msg[child.tag] = smart_str(child.text)
            return msg


def ReplyMsg(request):
        xmls = smart_str(request.body)
        xmldoc = ET.fromstring(ET.tostring(xmls,encoding='utf8', method='xml'))
        msgdict = parsexml(xmldoc)
        if msgdict['mstype'] == 'hello':
            return textReply(msgdict['fromusername'],msgdict['tousername'],msgdict['createtime'],'签到成功')

hello报文

<xml>
 <tousername><![CDATA[touser]]></tousername>
 <fromusername><![CDATA[fromuser]]></fromusername>
 <fromstudentnumber><![CDATA[fromstudentnumber]]></fromstudentnumber> 
 <createtime>1348831860</createtime>
 <msgtype><![CDATA[hello]]></msgtype>
 <helloid><![CDATA[hello id]]></helloid>
 <msgid>1234567890123456</msgid>
 </xml>
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/724
 
4155 次点击  
文章 [ 1 ]  |  最新文章 10 年前
Hiro_Fu
Reply   •   1 楼
Hiro_Fu    10 年前

把你打xml文件里面的空格和换行都去掉试试?