python xml 處理

來源:互聯網
上載者:User

標籤:findall   list   body   ack   iter   note   color   lte   節點   

import xml.etree.ElementTree as ET‘‘‘xml處理模組‘‘‘from idlelib.IOBinding import encoding  tree = ET.parse("xmltest.xml")#擷取rootroot = tree.getroot()print(root)#遍曆xmlfor child in root:    print(child.tag,child.attrib)    for i in child:        print(i.tag,i.text)#只遍曆body 節點for node in root.iter(‘body‘):    print(node.tag,node.text)        ‘‘‘修改‘‘‘for node in root.iter(‘from‘):#修改text    node.text="newValue" #修改屬性    node.set("test","2")tree.write("xmltest.xml")        ‘‘‘刪除‘‘‘for node in root.findall(‘heading‘):    root.remove(node)    tree.write("xmltest_delete.xml")                ‘‘‘建立‘‘‘ new_xml = ET.Element("nameList")info= ET.SubElement(new_xml,"info",attrib={"encrypt":"yes"})name = ET.SubElement(info,"name")age = ET.SubElement(info,"age")age.text= ‘23‘name.text = "jack"info2 = ET.SubElement(new_xml,"info",attrib={"encrypt":"no"})age = ET.SubElement(info2,"age")name = ET.SubElement(info2,"name")age.text= ‘25‘name.text = "flack"et = ET.ElementTree(new_xml)et.write("new_xml.xml",encoding="utf-8",xml_declaration=True)ET.dump(new_xml)

 

xmltest.xml:
<note>   <to>Tove</to>    <from test="1">www</from>    <heading>Reminder</heading>     <heading>adwwwee</heading>    <body>Don‘t forget me this weekend!</body>    <body>aaaaaaaaaa</body>    <body>bbbbbbbbbbb</body>    <body>     <test>cccccccccc</test>   </body> </note>

 

python xml 處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.