从零开始的Linux运维屌丝之路,资源免费分享平台   运维人员首选:简单、易用、高效、安全、稳定、社区活跃的开源软件

35、 XML模块 处理创建

发布:蔺要红05-24分类: Python


处理   修改  删除   生成


XML 指可扩展标记语言(eXtensible Markup Language)
XML 被设计用来传输和存储数据



XML文件内容: system.xml:

<info>
	<provinces name="山东">
		<rank city="临沂">linyi</rank>
		<year>2019</year>
		<gdppc>11232345234</gdppc>
		<neighor name="鲁"  direction="371326">123</neighor>
		<neighar name="Q"  direction="203"/>
	</provinces>
	<provinces name="青岛">
		<rank city="崂山">qingdao</rank>
		<year>2018</year>
		<gdppc>9999999999999</gdppc>
		<neighor name="海"  direction="371327"/>
		<neighar name="D"  direction="204"/>
	</provinces>
	<provinces name="北京">
		<rank city="五环">wuhuan</rank>
		<year>2017</year>
		<gdppc>7777777777777</gdppc>
		<neighor name="北"  direction="371328"/>
		<neighar name="B"  direction="205"/>
	</provinces>
</info>


XML模块处理XML文件:
 
# -*- coding:utf-8 -*-
import xml.etree.ElementTree  as ET
tree = ET.parse('system.xml') #打开
root = tree.getroot()  #f.seek(0)从头读取文件

print(root)    #<Element 'info' at 0x0000024DAC7E9C78> 

print(dir(root)) 
#['__class__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'attrib', 'clear', 'extend', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'iter', 'iterfind', 'itertext', 'keys', 'makeelement', 'remove', 'set', 'tag', 'tail', 'text']

print(root.tag)    #info

#D:\python\python.exe F:/运维笔记/python/模块/xml模块.py
<Element 'info' at 0x0000020E67799C78>
['__class__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', 
'__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__len__',
 '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__setstate__',
 '__sizeof__', '__str__', '__subclasshook__', 'append', 'attrib', 'clear', 'extend', 'find', 'findall', 'findtext', 'get', 
'getchildren', 'getiterator', 'insert', 'items', 'iter', 'iterfind', 'itertext', 'keys', 'makeelement', 'remove', 'set', 
'tag', 'tail', 'text']
info
# -*- coding:utf-8 -*-
import xml.etree.ElementTree  as ET
tree = ET.parse('system.xml') #打开
root = tree.getroot()  #f.seek(0)
#遍历xml文件
for child in root:
    print("-------------",child.tag,child.attrib) #
    for i in child:
        print(i.tag,i.text)

#D:\python\python.exe F:/运维笔记/python/模块/xml模块.py
------------- provinces {'name': '山东'}
rank linyi
year 2019
gdppc 11232345234
neighor 123
neighar None
------------- provinces {'name': '青岛'}
rank qingdao
year 2018
gdppc 9999999999999
neighor None
neighar None
------------- provinces {'name': '北京'}
rank wuhuan
year 2017
gdppc 7777777777777
neighor None
neighar None
# -*- coding:utf-8 -*-
import xml.etree.ElementTree  as ET
tree = ET.parse('system.xml') #打开
root = tree.getroot()  #f.seek(0)
#只遍历year节点
for node in root.iter('year'):
    print(node.tag,node.text)

#D:\python\python.exe F:/运维笔记/python/模块/xml模块.py
year 2019
year 2018
year 2017


XML模块
修改XML文件:

 
# -*- coding:utf-8 -*-
import xml.etree.ElementTree  as ET
tree = ET.parse('system.xml') #打开
root = tree.getroot()  #f.seek(0)
#修改
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)
    node.set("add_year_set","yes") #
tree.write("test.xml")

修改之后的XML文件:
 
<info>
	<provinces name="&#23665;&#19996;">
		<rank city="&#20020;&#27778;">linyi</rank>
		<year add_year_set="yes">2020</year>   #text增加了1  set添加了attrib
		<gdppc>11232345234</gdppc>
		<neighor direction="371326" name="&#40065;">123</neighor>
		<neighar direction="203" name="Q" />
	</provinces>
	<provinces name="&#38738;&#23707;">
		<rank city="&#23810;&#23665;">qingdao</rank>
		<year add_year_set="yes">2019</year>   #text增加了1  set添加了attrib
		<gdppc>9999999999999</gdppc>
		<neighor direction="371327" name="&#28023;" />
		<neighar direction="204" name="D" />
	</provinces>
	<provinces name="&#21271;&#20140;">
		<rank city="&#20116;&#29615;">wuhuan</rank>
		<year add_year_set="yes">2018</year>    #text增加了1  set添加了attrib
		<gdppc>7777777777777</gdppc>
		<neighor direction="371328" name="&#21271;" />
		<neighar direction="205" name="B" />
	</provinces>
</info>

XML模块删除XML文件的内容:
 
# -*- coding:utf-8 -*-
import xml.etree.ElementTree  as ET
tree = ET.parse('system.xml') #打开
root = tree.getroot()  #f.seek(0)
#删除
for country in root.findall("provinces"):
    year = int(country.find('year').text)
    if year < 2019:
        root.remove(country)
tree.write("del.xml")

删除内容以后的XML文件:
 
#只剩下一个、year<2019的都被删除
<info>
	<provinces name="&#23665;&#19996;">
		<rank city="&#20020;&#27778;">linyi</rank>
		<year>2019</year>
		<gdppc>11232345234</gdppc>
		<neighor direction="371326" name="&#40065;">123</neighor>
		<neighar direction="203" name="Q" />
	</provinces>
</info>

生成XML文件:
 
# -*- coding:utf-8 -*-
import xml.etree.ElementTree  as ET
root = ET.Element("info") #root
#创建name
name = ET.SubElement(root,"name",attrib={"enrolled":"yes"})
#创建name下的name
na = ET.SubElement(name,"name",attrib={"A":"c"})
na.text = "Lin"
#创建name下的age
age = ET.SubElement(name,"age",attrib={"checked":"no"})
age.text = "22"
sex = ET.SubElement(name,"sex",attrib={"AAA":"CCC"})
#创建sex下的AAA
sex2 = ET.SubElement(sex, "MM", attrib={"MMM": "M"})
sex3 = ET.SubElement(sex, "GG", attrib={"GGG": "G"})
#创建name下的server
nb = ET.SubElement(name,"server",attrib={"Nginx":"YES"})

et = ET.ElementTree(root)
et.write("new.xml",encoding='utf-8',xml_declaration=True)
ET.dump(root)

XMLXML文件内容:
 
<?xml version='1.0' encoding='utf-8'?>
<info>
    <name enrolled="yes">
        <name A="c">Lin</name>
        <age checked="no">22</age>
        <sex AAA="CCC">
            <MM MMM="M" />
            <GG GGG="G" />
        </sex>
        <server Nginx="YES" />
    </name>
</info>
温馨提示如有转载或引用以上内容之必要,敬请将本文链接作为出处标注,如有侵权我会在24小时之内删除!

欢迎使用手机扫描访问本站