【简明的Python】XML文档的解析、修改与重写

有这么样一个XML文件,文件名为test.xml

<?xml version="1.0"?>
<stop>
	<id>1</id>
    <name>wind</name>
    <city>
    	<province>hubei</province>
        <name>wuhan</name>
    </city>
    <hair>black</hair>
    <looks>
    	<weight>55Kg</weight>
        <height>175cm</height>
    </looks>
</stop>

下面采用ElementTree这个库来读取这个文档并进行解析、修改和重写操作

>>> from xml.etree.ElementTree import parse,Element
>>> doc=parse('test.xml') #解析文档
>>> root=doc.getroot()    #打开句柄
>>> root
<Element 'stop' at 0x036E0A78>
>>> # 删除id节点
>>> root.remove(root.find('id'))
>>> #插入hobby节点
>>> e=Element('hobby')
>>> e.text='basketball'
>>> root.insert(2,e)
>>> #将改变后的XML文本写回到test.xml文件中
>>> doc.write('test.xml',xml_declaration=True)
>>> 

现在test.xml的内容成了这样

<?xml version='1.0' encoding='us-ascii'?>
<stop>
	<name>wind</name>
    <city>
    	<province>hubei</province>
        <name>wuhan</name>
    </city>
    <hobby>basketball</hobby>
    <hair>black</hair>
    <looks>
    	<weight>55Kg</weight>
        <height>175cm</height>
    </looks>
</stop>

以上,就是XML文档的解析、修改和重写步骤的演示。

猜你喜欢

转载自blog.csdn.net/qq_42229092/article/details/107732183