一、python解析xml字符串
from xml.dom.minidom import parseString
xml_str="""
UAP_2oSY90
0410000043
旧部门
0410000043
9999
1
1
0432000000
新部门
0410000043
9999
1
1
0432000000
"""
doc = parseString(xml_str)
collection = doc.documentElement
returnInfo = collection.getElementsByTagName("deptName")[0].childNodes[0].data
# 返回的是:天
dataType=collection.getElementsByTagName("syncContent")[0].getAttribute("dataType")
operType=collection.getElementsByTagName("syncContent")[0].getAttribute("operType")
#返回的是:1
#获取节点名称,查找元素
for i in collection.getElementsByTagName("deptName"):
print (i.childNodes[0].data)
#返回:旧部门
# 新部门
oldContents = collection.getElementsByTagName("oldContent")
for oldContent in oldContents:
baseInfos = oldContent.getElementsByTagName('baseInfo')
for baseInfo in baseInfos:
baseInfo.getElementsByTagName('deptName')[0].childNodes[0].data
2、xml转json的函数
import json
import xmltodict
#定义xml转json的函数
xmlstr ="""
UAP_2oSY90
0410000043
旧部门
0410000043
9999
1
1
0432000000
新部门
0410000043
9999
1
1
0432000000
"""
#parse是的xml解析器
xmlparse = xmltodict.parse(xmlstr)
#json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。
#dumps()方法的ident=1,格式化json
jsonstr = json.dumps(xmlparse,indent=1)
print(jsonstr)