博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python---xml
阅读量:5306 次
发布时间:2019-06-14

本文共 1772 字,大约阅读时间需要 5 分钟。

'''import xml.etree.ElementTree as etreeElementTree is default python module, but it is slow, function is limitedso , we can import etree from lxml, it has the same api.'''from lxml import etree'''import lxml.etree as etreeit has the same function like above'''def getinfo1(path):    tree = etree.parse(path)    root = tree.getroot()    print('========root========')    print(root)    print(len(root))    print('=======tag============')    print(root.tag)    print('=========child===========')    for child in root:        print(child)    print('======attribute=========')    print(root.attrib)    print('======attribute1========')    print(root[0].attrib)    print(root[1].attrib)    print('======findall=========')    all1=root.findall('{http://www.w3.org/2005/atom}title')    print(all1)        print(all1[0].find('{http://www.w3.org/2005/atom}des'))    print(len(all1))    '''    findall, return list    find, return the first matched    '''    print('==========findall2==================')    all2=tree.findall('//{http://www.w3.org/2005/atom}*[@href]')    print(all2)    '''    // means all xml file, not just root or its children    * means any item    [@href] means include href as attribute    '''def writeinfo1(path):    root = etree.Element('root', lang='en')    sub1=etree.SubElement(root, 'title', color='##FFFFFF')    sub2= etree.SubElement(root, 'author', color = '##000000')    sub2.set('color','##AAAAAA')    sub1.set('type','text/html')    sub1.text='the content of title will be added'    print(etree.tostring(root, pretty_print=True))    with open(path, mode='wb') as file:        file.write(etree.tostring(root))if __name__ == '__main__':    getinfo1('xml_util.xml')    writeinfo1('xml_util2.xml')

 

转载于:https://www.cnblogs.com/xfei-zhang/p/5086837.html

你可能感兴趣的文章
河南省第十届ACM省赛G:Plumbing the depth of lake
查看>>
Elevator
查看>>
Mr. Frog’s Game(模拟连连看)
查看>>
JSON TO JOBJECT转换的使用方法
查看>>
几种常用的JS类定义方法
查看>>
如何理解环境光?
查看>>
EditText点击出现光标但不弹出软键盘
查看>>
HTTP状态码
查看>>
iOS如何过滤掉文本中特殊字符
查看>>
python - wmi模块学习(windwos硬件信息获取)
查看>>
FFmpeg命令行工具学习(四):FFmpeg 采集设备
查看>>
HTML5系列一(属性概述)
查看>>
大话设计模式--Python
查看>>
HOW TO UPGRADE GHOST ON OPENSHIFT
查看>>
python之路:数据类型初识
查看>>
Maven------使用maven新建web项目出现问题 项目名称出现红色交叉
查看>>
基础学习:C#中float的取值范围和精度
查看>>
Akka-Cluster(3)- ClusterClient, 集群客户端
查看>>
java中基本数据类型和包装类的区别
查看>>
项目指南
查看>>