python xml模块
生活随笔
收集整理的這篇文章主要介紹了
python xml模块
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
'''
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()
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()
轉載于:https://www.cnblogs.com/lides/p/11116713.html
總結
以上是生活随笔為你收集整理的python xml模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: centos 7.3 开放端口并对外开放
- 下一篇: 新车买车险注意事项 这几点一点要留意