xml.etree.ElementTree

x m l . e t r e e . E l e m e n t T r e e xml.etree.ElementTree xml.etree.ElementTree是是一个用于处理树结构的 P y t h o n Python Python 包,它可以用于处理任何树结构的数据,但最常用于处理 X M L XML XML 文档。

举例用XML文档


<fcd-export xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/fcd_file.xsd">
    <timestep time="0.00">
        <vehicle id="0.0" x="-94.90" y="-8.00" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="5.10" lane="-E2_0" slope="0.00"/>
        <vehicle id="1.0" x="11.20" y="-94.90" angle="0.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="5.10" lane="-E1_0" slope="0.00"/>
        <vehicle id="3.0" x="-11.20" y="94.90" angle="180.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="5.10" lane="-E3_0" slope="0.00"/>
        <vehicle id="5.0" x="94.90" y="8.00" angle="270.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="5.10" lane="-E0_0" slope="0.00"/>
    timestep>
    <timestep time="100.00"/>
    <timestep time="200.00"/>
fcd-export>

以其中的一行为例:

<vehicle id="0.0" x="-94.90" y="-8.00" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="5.10" lane="-E2_0" slope="0.00"/>

在这一行里, v e h i c l e vehicle vehicle就是 t a g tag tag,而其中的 i d id id x x x y y y之类的就是 a t t r i b u t e attribute attribute

导入文档

import xml.etree.ElementTree as ET
tree = ET.parse("NameOfDocument.xml")
root = tree.getroot()

r o o t root root里面就包含了所有的子节点

遍历节点

意外的直接简单的使用 f o r for for循环就可以

for child in root:

在样例里面,一重循环只能遍历所有的 t i m e s t e p timestep timestep。那如果想要遍历 v e h i c l e vehicle vehicle呢?那就要用二重循环,找到子节点里面的子节点。

for child in root:
    if (child.tag == 'timestep'):
        for child2 in child:

一些修改操作

调用属性

用实际代码演示一下好了

for child in root:
    for child2 in child:
        if (child2.tag == 'vehicle'):
            a = (child2.attrib)
            speeds[c] = np.float(a['speed'])
            ids[c] = np.float(a['id'])
            times[c] = t
            c = c + 1
    t = t + 1

上面的代码实现了利用 i f if if语句筛选所需要的数据,然后用 a a a存储了这一行数据所有的属性,然后调用了这些属性。

修改属性

for child in root:
    if (child.tag == 'vehicle'):
        for child2 in child:
            child2.attrib['speed'] = str(1.0)
with open('NameOfDocument.xml', 'wb') as f:
    tree.write(f)

注意 x m l xml xml文件里面的数值都是字符串形式。仅仅这么修改是不会作用到文件本身的,所以就利用 w i t h   o p e n   a s with\ open\ as with open as来对 x m l xml xml文件进行写入。

你可能感兴趣的:(Python,xml)