Exemplo n.º 1
0
# -*- coding: utf-8 -*-
# Author: hkey
import xml.etree.ElementInclude as ET

tree = ET.parse('test.xml')
root = tree.getroot()
print(root.tag)

# 遍历xml文件
def traverseXml(element):
    # print (len(element))
    if len(element) > 0:
        for child in element:
            print(child.tag, "----", child.attrib)
            traverseXml(child)


if __name__ == "__main__":
    xmlFilePath = os.path.abspath(
        "F:/Github/DL-data-processing-methods/XML/test.xml")
    print(xmlFilePath)
    try:
        tree = ET.parse(xmlFilePath)
        print("tree type:", type(tree))

        # 获得根节点
        root = tree.getroot()
    except Exception as e:  # 捕获除与程序退出sys.exit()相关之外的所有异常
        print("parse test.xml fail!")
        sys.exit()
    print("root type:", type(root))
    print(root.tag, "----", root.attrib)

    # 遍历root的下一层
    for child in root:
        print("遍历root的下一层", child.tag, "----", child.attrib)

    # 使用下标访问