'''
XML格式
首先,来看一下XML所包含的元素类型
1. 标签 <tag>
2. 属性 <tag name="attribute">
3. 数据 <data>1<data>
'''
import xml.etree.cElementTree as et
file_path = "xml_text.xml"
'''
创建xml文件
'''
def create_xml():
# 创建根节点
root = et.Element('data')
# 向父节点添加子节点
country1 = et.SubElement(root,'country')
# 给节点添加属性
country1.attrib = {'name':'Austria','direction': 'E'}
son = et.SubElement(country1, 'son')
son.attrib={"name":"test"}
son.text="test"
# 创建elementtree对象
tree = et.ElementTree(root)
# 写入文件
tree.write(file_path)
'''
读取xml文件或字符
'''
def read_xml():
str_xml = '''<data><country direction="E" name="Austria"><son name="test">test</son></country></data>'''
# 将xml字符串转为element
root = et.fromstring(str_xml)
# 读取xml文件转为ElementTree对象
# tree = et.parse(file_path)
# root = tree.getroot()
for i in root:
print( i.tag)
print(i.attrib)
print(i.text)
# 查找第一个标签为son的元素
print(i.find("son"))
# 查找所有标签为son的元素
print(i.findall('son'))
# 遍历所有标签为son的元素
for j in i.iter('son'):
print(j)
'''
修改xml
'''
def modify_xml():
tree = et.parse(file_path)
root = tree.getroot()
country = root.find("country")
son = country.find("son")
# 设置属性
son.set('name','newvalue')
# 设置text值
son.text='newtext'
tree.write(file_path)
if __name__ == '__main__':
# create_xml()
# read_xml()
modify_xml()