zoukankan      html  css  js  c++  java
  • python学习之

    xml模块
    定义:实现不同语言或程序之间进行数据交换的协议。
    格式如下:通过<>节点来区别数据结构
    如:<load-on-startup(这个是标签) test="value"(这个是属性)>5(这个是文本)</load-on-startup>
    root.tag:打印标签
    root.attrib:打印属性
    root.text:打印文本
    举例:
    自定义一个stud.xml文件
    首先打印各级信息
    import xml.etree.ElementTree as et
    tree = et.parse('stud.xml') #文件名
    root = tree.getroot() #提取根节点
    print(root.tag) #打印根标签
    1.#遍历xml文档
    for child in root:
    print(child.tag,child.attrib,child.text) #打印二级节点标签
    for i in child:
    print(i.tag,i.attrib,i.text) #打印三级节点标签
    2:#查找param-name节点
    for node in root.iter('param-name'):
    print(node.tag,node.attrib,node.text)
    #打印:load-on-startup {} 4
    3:# 修改使load-on-startup 值加1
    for node in root.iter('load-on-startup'): #遍历
    new = int(node.text)+1 #匹配load-on-startup值4加1
    node.text = str(new) #将新值5替换源值4
    node.set('test','value') #为load-on-startup增加属性(test="value")
    tree.write('stud.xml') #将修改保存回xml文件
    4: 删除操作
    for country in root.findall('country'):
    rank = int(country.find('rank').text)
    if rank > 50:
    root.remove(country)
    tree.write('out.xml')
    4:#创建xml文件
    import xml.etree.ElementTree as et
    #创建根节点
    rootlist = et.Element('tech')
    #创建二级节点
    tech = et.SubElement(rootlist,'tech_node',attrib={'name':'tech_center'})
    #创建三级节点
    dev = et.SubElement(tech,'dev_node',attrib={'name':'dev_center'})
    #写内容
    dev.text = 'java'
    dev.text = 'python'
    test = et.SubElement(tech,'test_node',attrib={'name':'test_center'})
    test.text = 'program'
    #创建二级节点
    finance = et.SubElement(rootlist,'finance_node',attrib={'name':'finance_center'})
    #创建三级节点
    account = et.SubElement(finance,'account_node',attrib={'name':'account_center'})
    account.text = 'woman'
    #生成文档对象
    obj = et.ElementTree(rootlist)
    # 写文件,xml_declaration就是自动在xml文件头加声明
    obj.write('stud3.xml',encoding='utf-8',xml_declaration=True)
    #可选的屏幕打印
    et.dump(rootlist)
  • 相关阅读:
    PHP数组处理总结
    设计模式之-工厂模式理解
    我的世界观
    编程入门
    2019 新的一年
    placeholder 不支持ie8
    2018年8月20日
    HttpClientUtil
    通用mapper
    small_demo
  • 原文地址:https://www.cnblogs.com/zy6103/p/6840819.html
Copyright © 2011-2022 走看看