python 使用element tree 解析 xml
推荐这个文档: https://docs.w3cub.com/python~2.7/library/xml.etree.elementtree
基本概念
- ElementTree 代表把整个xml作为一棵树处理
- Element 代表树中的一个节点
- 整体操作,如文件读写,多用ElementTree, 具体解析和修改多用Element
不同的读取方式
tree = ET.parse('country_data.xml')从文件读取xml,返回一个 ElementTree。 使用root = tree.getroot()返回根节点Elementroot = ET.fromstring(country_data_as_string)从字符串加载xml,直接返回根节点Element
常用方法
deviceETString = ET.tostring(deviceET, encoding='utf-8')第一个参数是Element, 把其中的xml以字符串返回。要注意的是,如果在python2 中指定encoding 为 unicode,会报错unknown encoding: unicode, 参考 https://stackoverflow.com/questions/15304229/convert-python-elementtree-to-stringET.dump(element)直接把Element包含的xml打印出来,相当于printElement.tagtag属性可以区分不同类型的节点,使用中发现tag会带上命名空间,比如{namespace:abc:xyz}Components, 大括号中的内容为命名空间xmlns:="namespace:abc:xyz"Element.attribattrib属性是一个包含当前Element所有属性的字典。比如<Components xmlns="namespace:abc:xyz" id="weee" name="1ee2">, 字典内容应该是:{'id':"weee", 'name':"1ee2"}Element.find(param)以及Element.findall(param),find找第一个匹配,findall返回所有匹配的列表。他们的参数都一样,是一个tag或者路径,比如find("{namespace:abc:xyz}Components/{namespace:abc:xyz}Device")会找到{namespace:abc:xyz}Components标签下,所有类型为{namespace:abc:xyz}Device的子标签。

浙公网安备 33010602011771号