Bootstrap

python3.7 解析XML超简单的方法

#更新各品种行情时间
import json
import xml.etree.ElementTree as ET
import redis

#这是例子,注意编码格式必须是utf-8否则会报错。
# <?xml version="1.0" encoding="utf-8"?>
# <tradetime>
#     <item productid="c" timestring="21:00-23:00, 9:00-10:15, 10:30-11:30, 13:30-15:00" exchangeid="DCE" />
#     <item productid="CY" timestring="21:00-23:30, 9:00-10:15, 10:30-11:30, 13:30-15:00" exchangeid="CZCE" />
#     <item productid="FG" timestring="21:00-23:30, 9:00-10:15, 10:30-11:30, 13:30-15:00" exchangeid="CZCE" />
# </tradetime>

host = '127.0.0.1'
password = ''

#连接redis,可要可不要,我是为了存在redis中用
rp = redis.StrictRedis(host=host, db=2, password=password)
tree = ET.parse("timestring.xml") #xml名字
saveData = {}
root = tree.getroot()  #得到第一层的节点
for i in root:         #遍历第一层节点
    # for t in i:      #遍历第二层
    saveData['timestring'] = i.attrib['timestring'] #获取属性值
    saveData['exchangeid'] = i.attrib['exchangeid']
    rp.hset('timestring',i.attrib['productid'],json.dumps(saveData))
    saveData = {}

 

;