1. xml創建,網上教程很多,但有些暗坑還是要記下來
a. xml第一行的standalone無法通過屬性設置,最好是自己設置然後拼接
2.xml解析
a.url 返回的字符集有可能不是utf-8的,會導致解析xml的時候出錯,因此需要解析字符集編碼爲utf-8
b.xml中的encoding必須="utf-8",如果不是,需要自己使用字符串方法替換爲utf-8
from xml.etree import ElementTree as ET
import requests
from pydoc import doc
import collections
url='http://xx.xx.x.x:xx/xx/xx/active?msg='
def xml_building(num,sys_id='8888',cmd_id='test'):
#含有默認值的參數放在不含默認值的參數前邊會有歧義
'''
xml 構建
xml第一行的standalone無法通過屬性設置,最好是自己設置然後拼接
http://stackoverflow.com/questions/3982887/how-to-add-xml-header-to-dom-object
'''
#存儲字符串
str_list=[]
#xml第一行
str_list.append('<?xml version="1.0" encoding="GB2312" standalone="yes"?>')
#root
root=ET.Element('command')
sysid=ET.SubElement(root,'sysid')
sysid.text=sys_id
cmdid=ET.SubElement(root,'cmdid')
cmdid.text=cmd_id
#subchild
params=ET.SubElement(root,'params')
phonenum=ET.SubElement(params,'phonenum')
phonenum.text=num
xml_string=ET.tostring(root)
str_list.append(xml_string)
return ''.join(str_list)
def xml_get(url):
try:
url=url.encode('utf-8')
r=requests.get(url,timeout=30)
'''
url 返回的字符集有可能不是utf-8的,會導致解析xml的時候出錯,因此需要解析字符集編碼爲utf-8
'''
return r.text.encode('utf-8')
except requests.exceptions.RequestException as e:
raise e
def xml_replace_header(xml_str):
try:
'''xml解析的時候要求encoding=utf-8
'''
return xml_str.replace('encoding="GB2312"','encoding="utf-8"')
except Exception as e:
raise e
def xml_parsing(xml):
'''
xml解析
'''
try:
xml_tuple=collections.namedtuple('xml_tuple','sysid,cmdid,resultnum, reason')
doc=ET.ElementTree(ET.fromstring(xml))
resultnum=doc.find('result_num')
reason=doc.find('reason')
xml_tuple.resultnum=resultnum.text
xml_tuple.reason=reason.text
return xml_tuple
except Exception as e:
raise e