python创建和解析XML

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值