ImportXml.etree.ElementTree as ET" "XML Processing Module" " fromIdlelib. IobindingImportEncoding Tree= Et.parse ("Xmltest.xml")#Get RootRoot =tree.getroot ()Print(Root)#traversing XML forChildinchRoot:Print(Child.tag,child.attrib) forIinchChild :Print(I.tag,i.text)#Traverse only the body node forNodeinchRoot.iter ('Body'): Print(Node.tag,node.text)" "Modify" " forNodeinchRoot.iter (' from'):#Modify Textnode.text="NewValue" #Modifying PropertiesNode.set ("Test","2") Tree.write ("Xmltest.xml") " "Delete" " forNodeinchRoot.findall ('Heading'): Root.remove (node) tree.write ("Xmltest_delete.xml") " "Create" "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=' at'Name.text="Jack"Info2= ET. Subelement (New_xml,"Info", attrib={"Encrypt":"No"}) age= ET. Subelement (Info2," Age") name= ET. Subelement (Info2,"name") Age.text=' -'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> < fromTest= "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 processing