1 #Coding=utf-82 fromXml.etreeImportElementTree3 4 ImportPDB5 6 defprintnodeinfo (node):7 8 #Node.tag Label name9 #Node.text Text PropertiesTen Print 'Node.tag:%s'%Node.tag One A #Node.attrib Property Dictionary - forKeyinchNode.attrib: - Print '%s%s'%(Key,node.attrib[key]) the returnNone - - defMain (): - + pdb.set_trace () - Try: + #elementtree.parse (Source,parser=none) A #loads the XML file and returns the ElementTree object at #parser is an optional parameter that uses the standard xmlparser if it is empty - #Step 1: Get the ElementTree object -xmldoc = Elementtree.parse ('D:\server\map\App.xml') - #Step 2: Get the root node -Root =xmldoc.getroot () - #Root.getchildren () Gets the list returned by the node inGateservernodelist =Root.getchildren () - to #here is the addition of a child node under each gateserver node + forNodeinchgateservernodelist: - #elementtree.subelement (parentnode,tagname) the #Add a child node to a parentnode * #consistent with parentnode.append (Element) Effect $NewNode = elementtree.subelement (node,'Activetype')Panax Notoginseng #Setting Properties -newnode.attrib['ID'] ='9' thenewnode.attrib[' Level'] =' -' +newnode.attrib['begin'] ='201401010000' Anewnode.attrib['End'] ='201401010000' the #Chinese need special decoding +newnode.attrib['Tip'] ='Test'. Decode ('Utf-8') - #symbol at the end of a node $Newnode.tail ='\ n' $ #node.append (NewNode) - - #writes the ElementTree object before the file is called . the #Write (filename,encoding = None,xml_decleare = None,default_namespace = None,method = None) - #where Xml_decleare is True, it is written at the top of the documentWuyi #<?xml version= "1.0" encoding= "Utf-8"?> theXmldoc.write ('D:test.xml','Utf-8', True) - exceptException as E: Wu Printe - About returnNone $ - if __name__=='__main__': -Main ()
Create an XML file with Python