xml使用<xml.etree.ElementTree>操作數(shù)據(jù)
- 讀取xml字符串
網(wǎng)上大多教程是從文本中讀取,我這里只是需要處理xml字符串,因此直接在代碼中加載,如下:
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
content = '''<?xml version="1.0" encoding="GBK"?>
<request>
<head>
<name>測試</name>
<age>22</age>
<sex></sex>
</head>
<body>
<happy>哈哈</happy>
<time>666</time>
</body>
</request>'''
- 加載字符串
在此處遇到一問題,就是因?yàn)閤ml頭部是gbk格式,因此加載報(bào)錯(cuò),此處先暫時(shí)替換掉了GBK為utf-8
content = content.replace('GBK', 'utf-8').replace('gbk', 'utf-8')
tree = ET.fromstring(content)
print tree # 打印root節(jié)點(diǎn)元素
print tree.find('body') # 打印<request>下的body節(jié)點(diǎn)
name = tree[0].find('name') # 獲取head節(jié)點(diǎn)下的name節(jié)點(diǎn)
name.text = 'This is a test' # 修改name節(jié)點(diǎn)的名字
print tree[1] # 打印<request>下的第二個(gè)節(jié)點(diǎn),也就是body節(jié)點(diǎn)
tree.remove(tree[0]) # 移除request下標(biāo)的第一個(gè)節(jié)點(diǎn),即head
print tree.tag
print tree[0].tag
print tree[0].text
e = ET.Element('spam')
e.text = 'This is a test'
tree.insert(1, e) # 此處新增元素加在哪里,只需要將tree替換成需要添加的元素節(jié)點(diǎn)
print ET.tostring(tree) # tree是打印的全部xml字符串,換成對應(yīng)的節(jié)點(diǎn),可以打印當(dāng)前節(jié)點(diǎn)下的數(shù)據(jù)。PS:此處不帶xml頭部,最后需要手動(dòng)添加
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。