Python解析XML配置文件

ElementTree模块

    • 1、ElementTree模块
    • 2、读取与解析
    • 3、修改、写入、删除


1、ElementTree模块

ElementTree是Python处理XML文件的内置类,用于解析、查找和修改XML,ElementTree可以将整个XML文件解析成树形结构

单个Element的XML对应格式为:

'''
xxx
 tag attrib     text
'''
  • tag:XML标签,str对象
  • attrib:XML属性,dict对象
  • text:XML数据内容

例如test.xml文件:

'''


   
       cisco_ios
       admin
       cisco
       192.168.47.10
   
   
       huawei_vrpv8
       admin
       huawei
       192.168.47.30
   

'''

2、读取与解析

from xml.etree import ElementTree as ET

# 读取XML文件
tree = ET.parse(r'C:\Users\cc\Desktop\test.xml')
# 获取根信息
root = tree.getroot()
print(root.tag)        # dev_info
print(root.attrib)     # dev_info
print(root.text)
# 获取root的child层信息
for child in root:
    print(child.tag, child.attrib, child.text)
'''
R1 {'type': 'cisco'}
SW3 {'type': 'huawei'}
'''

ElementTree查找:

'''
iter(tag=None):遍历Element的child,可以指定tag精确查找
findall(match):查找当前元素tag或path能匹配的child节点
find(match):查找当前元素tag或path能匹配的第一个child节点
get(key,default=None):获取元素指定key对应的attrib,如果没有attrib,返回default
'''
for child in root.iter('password'):
    print(child.tag, child.attrib, child.text)
'''
password {} cisco
password {} huawei
'''
for child in root.findall('R1'):
    print(child.find('password').text)
'''
cisco
'''

3、修改、写入、删除

方法汇总:

'''
Element.text:修改数据内容
Element.remove(child):删除节点
Element.set(attrib,new_text):添加或修改属性attrib
Element.append(child):添加新的child节点
'''

修改完成后使用ElementTree.write()方法写入保存

# 修改R1的ip
for child in root.iter('R1'):
    child.find('ip').text = str('192.168.47.1')

tree.write(r'C:\Users\cc\Desktop\test.xml')

# 删除SW3的标签
for child in root.findall('SW3'):
    root.remove(child)

tree.write(r'C:\Users\cc\Desktop\test.xml')

你可能感兴趣的:(#,Python,#,自动化,python,xml)