python3读XML数据

来源:互联网 发布:tomcat启动 记录数据库 编辑:程序博客网 时间:2024/06/17 07:03
from xml.etree.ElementTree import parsef = open(r"C:\PlatformConfigure\Configure\VideoStreamingServerConfigure.xml")et = parse(f)root = et.getroot()     # 获取根节点print(root)# 第一种遍历根节点的子元素(该方法要取消了,不推荐使用)childs = root.getchildren()for child in childs:    print(child.tag)# 第二种遍历根节点的子元素for child in root:    print(child.tag)# 查找当前节点的子元素print(root.find('LocalIP'))  # 查找到第一个‘LocalIP’的元素print(root.findall('LocalIP'))  # 查找到所有标签是‘LocalIP’的元素,得到的是一个列表print(root.iterfind('LocalIP'))  # 查找到所有标签是‘LocalIP’的元素,得到的是迭代对象for e in root.iterfind('LocalIP'):    print(e.tag)# 列出所有节点元素for e in root.iter():    print(e.tag)# 查找指定标签的元素节点print(root.iter('LocalIP'))# 查找孙子节点print(root.findall('connstr/*'))print(root.findall('.//host'))     # 查找任意层次下的指定节点元素print(root.findall('.//host/..'))  # 查找任意层次下的指定节点元素的父元素print(root.findall('LocalIP[@age]'))   # 查找包含age属性的LocalIP节点元素print(root.findall('LocalIP[@age="18"]'))   # 查找包含age属性值=18LocalIP节点元素print(root.findall('connstr[host]'))      # 查找包含host节点的connstr节点元素for host in root.findall('.//host'):       # 输出节点的值    print(host.text)
原创粉丝点击