加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

【python小随笔】python解析xml格式字符串与xml文件

发布时间:2020-12-20 10:03:32 所属栏目:Python 来源:网络整理
导读:1:解析xml---文件 from xml.dom.minidom import parse xml.dom.minidom # 使用minidom解析器打开XML文档 DOMTree = xml.dom.minidom.parse( " ./test.xml " ) print (DOMTree)collection = DOMTree.documentElement 集合某个标签 VariationChilds = collect

1:解析xml---文件

from xml.dom.minidom import parse
 xml.dom.minidom

# 使用minidom解析器打开XML文档
DOMTree = xml.dom.minidom.parse("./test.xml")
print(DOMTree)
collection = DOMTree.documentElement


 集合某个标签
VariationChilds = collection.getElementsByTagName(ns2:VariationChild)

 取出集合标签下的数据
for VariationChild in VariationChilds:
    Asin = VariationChild.getElementsByTagName('ASIN')[0].childNodes[0].data
    color = VariationChild.getElementsByTagName(ns2:Color)[0].childNodes[0].data
    print(Asin,color)

2: ?解析xml---字符串

import parseString 导入解析字符串的包

xml_dom = parseString(xml_srt)  这里放你的xml数据,然后转换成xml.dom.minidom.Document对象,就可以进行上面的操作,
print(xml_dom)

3:完整代码(综合使用)

xml_data = MWSs.make_request(extra_data,POST).original
(xml_data)# 返回xml格式数据

 字符串转换成xml.dom.minidom.Document对象 xml_data是xml格式字符串
DOMTree = parseString(xml_data)

collection = DOMTree.documentElement
 集合你要的标签
VariationChilds = collection.getElementsByTagName( 进行遍历取值
(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读