您好,登錄后才能下訂單哦!
xmltest.xml內容如下:
<data>
<country name="Liechten">
<rank updated="yes">1</rank>
<year updated_by="Alex">2017</year>
<gdppc>140000</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
</data>
xml處理:
import xml.tree.ElementTree as ET
tree=ET.parse("xmltest.xml")
root=tree.getroot() #獲取根節點
print(root)
print(root.tag)
#遍歷xml
for child in root:
......print(child.tag,child.attrib) #打印孩子節點標簽和屬性
......for i in child:
............print(i.tag,i.text.i.attrib)
#只遍歷year節點
for node in root.iter('year')
......print(node.tag,node.text)
#xml修改
for node in root.iter('year'):
......new_year=int(node.text)
......node.text=str(new_year)
......node.set("updated_by","cai")
tree.write("xmltest.xml")
#刪除
for country in root.findall('country'):
......rank=int(country.find('rank').text)
......if rank>50:
..........root.remove(country)
tree.write('output.xml')
#自己編寫
import xml.etree.ElementTree as ET
new_xml=ET.Element("personinfolist")
personinfo=ET.SubElement(new_xml,"personinfo",attrib={"enrolled":"yes"})
name=ET.SubElement(personinfo,"name")
name.text="huaha"
age=ET.SubElement(personinfo,"age",attrib={"checked":"no"})
age.text='12'
et=ET.ElementTree(new_xml) #生成文檔對象
et.write("test.xml",encoding='utf-8',xml_declaration=True)
ET.dump(new_xml) #打印生成的格式
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。