前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python3读XML数据

python3读XML数据

作者头像
py3study
发布2020-01-09 10:42:14
8650
发布2020-01-09 10:42:14
举报
文章被收录于专栏:python3
代码语言:javascript
复制
from xml.etree.ElementTree import parse

f = 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属性值=18的LocalIP节点元素
print(root.findall('connstr[host]'))      # 查找包含host节点的connstr节点元素


for host in root.findall('.//host'):       # 输出节点的值
    print(host.text)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/08/24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档