# -*- coding:utf-8 -*-# https://zhuanlan.zhihu.com/p/54269963# from xml.etree import ElementTree as etreefrom xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from xml.etree.ElementTree import ElementTree
from xml.dom import minidom
# generate root node
root = Element('root')# generate first child-node head
head = SubElement(root,'head')# child-node of head node
title = SubElement(head,'title')
title.text ="Well Dola!"# generate second child-node body
body = SubElement(root,'body')
body.text ="I Love Dola!"
tree = ElementTree(root)# write out xml data
tree.write('result.xml', encoding='utf-8')
结果 :result.xml
<root><head><title>Well Dola!</title></head><body>I Love Dola!</body></root>
(2)在xml有根元素时写入
customer.xml
<customer ID="C003"><name>kavin</name><phone>32467</phone><comments><![CDATA[A small but healthy company.]]></comments></customer>
<?xml version="1.0" encoding="utf-8"?><customer ID="C003"><name>kavin</name><phone>32467</phone><comments><![CDATA[A small but healthy company.]]></comments><customer ID="C003"><name>kavin</name><phone>32467</phone><comments><![CDATA[A small but healthy company.]]></comments></customer></customer>
(3)xml的读取
movie.xml
<collection shelf="New Arrivals"><movie title="Enemy Behind"><type>War, Thriller</type><format>DVD</format><year>2003</year><rating>PG</rating><stars>10</stars><description>Talk about a US-Japan war</description></movie><movie title="Transformers"><type>Anime, Science Fiction</type><format>DVD</format><year>1989</year><rating>R</rating><stars>8</stars><description>A schientific fiction</description></movie><movie title="Trigun"><type>Anime, Action</type><format>DVD</format><episodes>4</episodes><rating>PG</rating><stars>10</stars><description>Vash the Stampede!</description></movie><movie title="Ishtar"><type>Comedy</type><format>VHS</format><rating>PG</rating><stars>2</stars><description>Viewable boredom</description></movie></collection>
# -*- coding=utf-8 -*-import xml.etree.cElementTree as ET
import os
defdeal_xml(xml_path):
tree = ET.parse(xml_path)
root = tree.getroot()for i in root:if i.tag =='path':
root.remove(i)
tree.write(xml_path)if __name__ =='__main__':
path = r"D:\pycharm\test\处理xml\xml"for i in os.listdir(path):
xml_path = os.path.join(path, i)
deal_xml(xml_path)