for child in root:print(child.tag, child.attrib)# 获取下一级的标签和属性for i in child:print(' ', i.tag, i.text)# 获取再下一级的标签和文本
# 只遍历epoch节点for node in root.iter('epoch'):# 在 根节点的子节点中过滤出标签‘epoch’print(node.tag, node.text)# 打印节点标签和文本
三 解析xml节点
import xml.etree.ElementTree as ET # 导入ElementTree模块
tree = ET.parse('train_config.xml')# 获取解析对象
root = tree.getroot()# 获取根节点print(root.tag)for child in root:print(child.tag, child.attrib)# 获取下一级的标签和属性for i in child:print(' ', i.tag, i.text)# 获取再下一级的标签和文本
四 修改xml节点
for node in root.iter('epoch'):
new_year =123# 修改获取到的文本 (先转为int 型)
node.text =str(new_year)# 再转为string 型
tree.write("train_config.xml")# 持久化