脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python读写xml文件实例详解嘛

python读写xml文件实例详解嘛

2022-10-20 11:32单单一个越字 Python

这篇文章主要为大家详细介绍了python读写xml文件的实例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

xml文件:country.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<data>
    <country name="shdi2hajk">231
        <rank>1<NewNode A="1">This is NEW</NewNode></rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" /> 
        <neighbor direction="W" name="Switzerland" />
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor direction="N" name="Malaysia" />
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor direction="W" name="Costa Rica" />
        <neighbor direction="E" name="Colombia" />
    </country>
    <MediaPlatformService height="165" ip="36.32.160.199" passWord="111" port="9084" userName="admin" width="220">
    </MediaPlatformService>
</data>

xml文件解读

?
1
2
3
4
5
6
7
8
1.xml一个节点有三个属性:tag、text、attrib
2. 以第一个子节点country为例:
3. tag代表节点名字,country节点的tag就是它的名字:country
4. text代表节点文本内容,rank节点的text就是1
5. attrib代表节点包含的属性,以{属性:值}这样的字典形式存放。country节点的属性是{name:Liechtenstein}.name是属性的键,Liechtenstein是属性的值。{属性:值}就是一个字典类型,可以使用一切字典方法。
6. country节点的tag为country,attrib为{name:Liechtenstein},text为空
7. rank节点的tag为rank,attrib为空字典,text为1
8. 综上所述,xml文档主要由节点以及节点的三个属性组成。

读取文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import xml.etree.ElementTree as ET
file_path = r'xml_te.xml'
tree = ET.ElementTree(file = file_path)  #读取xml文件
print(tree.iter())
for i in tree.iter('rank'):  #迭代获取tag为'rank'的节点
    print(i.text)
nodes = tree.find('country') #获取第一个tag为country的节点,返回是子节点的迭代对象
print(nodes.tag)
nodes2 = tree.findall('country') #获取所有tag为country的节点
print(nodes2)
for node in nodes2:
    #打印节点的三个属性
    print(node.tag)
    print(node.attrib)
    print(node.text)

增加新节点及修改属性值和文本

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import xml.etree.ElementTree as ET
file_path = r'xml_te.xml'
tree = ET.ElementTree(file = file_path)  #读取xml文件
 
# root = tree.getroot()  #获取根结点
"""增加新节点"""
net = ET.Element('NewNode')
net.attrib = {'A':"1"}   #节点属性
net.text = "This is NEW"   #节点文本
node = tree.find('country/rank/NewNode')   #找到需要增加子节点的父节点
node.append(net)
print(node.text)
tree.write(file_path)  #写入文件
"""修改属性值"""
sub = tree.find('country')   #找到节点
sub.set('name',"shdi2hajk"#set(key,new value)
sub.text = '231'
print(sub.attrib)
print(sub.text)
tree.write(file_path)  #写入文件

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容! 

原文链接:https://blog.csdn.net/qq_38122800/article/details/123208245

延伸 · 阅读

精彩推荐