Py学习  »  问与答

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

1160974245 • 9 年前 • 3412 次点击  

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
 
3412 次点击  
文章 [ 1 ]  |  最新文章 9 年前
Hiro_Fu
Reply   •   1 楼
Hiro_Fu    9 年前

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