简易化使用:
一、打开xml文件
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml') 这种方法最好配合try/except
root = tree.getroot()
或者:
推荐:
with open(xml_path, 'rt') as f:
tree = xml.etree.ElementTree.parse(f)
二、查找节点/元素
node = tree.find(".//*[name1=‘text1’]") 多级查找某个节点,该节点有一个叫name1的子节点并且子节点的文本区的值等于text1。find参数是XPATH语法,其中//表示在当前元素往下多级查找节点,*表示查找所有的一级子节点/元素。
syntax | meaning |
---|---|
// | Selects all subelements, on all levels beneath the current element (search the entire subtree). For example, “.//egg” selects all “egg” elements in the entire tree. |
* | Selects all child elements. For example, “*/egg” selects all grandchildren named “egg”. |
三、访问节点值
- node.tag node.attrib node.text 表示访问当前元素的一些信息。
node[0].text 访问当前元素中包含的第一个子元素的text值。
- 如果node指代root,则node[0].text 得到的值是\n\t,可用list函数查看这两个特殊的控制符号,如下xml,
text指的就是与<country…之间的文本内容,如果想查看元素中包含的子元素中的文本内容,可用函数itertext。
node[0][1].text 访问当前元素第一个子元素中第二个元素的text值。
- 如果node指代的当前元素是root根元素,则如下xml文件,node[0][1].text就是得到值2008:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>