Python basis of eight - with XML files (xml.etree.ElementTree)

1. 导入:import xml.etree.ElementTree as ET;

2. Obtain the xml file tree: tree = ET.parse ( "xml_test // xmltest.xml");

3. Obtain the file tree root xml: root = tree.getroot ();

4. traverse xml file:

  for elem in root:

    print(elem .tag,elem .attrib,elem .attrib['name'])  

    for sub_elem in elem:

     print(sub_elem .tag,sub_elem .attrib,elem .text) 

The traverse only 'name' nodes: for node in root.iter ( 'name');

6. Obtain all the specified nodes: root.findall ( "name");

7. Delete: root.remove (elem);

8. 新增节点:new_elem = ET.Element('new')-->new_elem.text = "new one"--->new_elem.attrib = {'up','yes'}--->elem.append(new_elem);

9. last written: tree.write ( 'xml_test \\ a.xml.swap').

 

Guess you like

Origin www.cnblogs.com/gangzi4321/p/10953107.html