python3读XML数据

发布时间:2019-08-24 09:21:16编辑:auto阅读(1259)

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

关键字