Python XML attributes/node/text additions and deletions [Xml.etree.elementtree]__python

Source: Internet
Author: User

http://blog.csdn.net/wklken/article/details/7603071

========================

Demand:

In practical application, the XML configuration file needs to be modified in real time.

1. Add and remove certain nodes

2. Add, delete, modify some properties under a node

3. Add, delete, modify the text of some nodes


XML source file format [Example][HTML] View Plain copy print? <?xml version= "1.0"  encoding= "UTF-8"?>   <framework>        <processers>           <processer  Name= "Aprocesser"  file= "lib64/a.so"                 path= "/tmp" >           </processer >           <processer name= "Bprocesser"  file = "lib64/b.so"  value= "Fordelete" >           </ processer>           <processer name= "BProcesser"  file= "lib64/b.so2222222"/>                      <services>       &nbsP;       <service name= "Search"  prefix= "/bin/search?"                     Output_formatter= "Outputformatter:service_inc" >                                        <chain sequency= "Chain1"/>                    <chain sequency= " Chain2 "></chain>                </service>               < Service name= "Update"  prefix= "/bin/update?" >                   <chain sequency= "chain3"  value= "Fordelete"/>                </service>            </services>       </processers>    </framework>  
Working with libraries:

Xml.etree.ElementTree

Official Document Address: http://docs.python.org/library/xml.etree.elementtree.html


To realize the idea:

Using ElementTree, first read the file into, parse into a tree, then, according to the path, you can navigate to each node of the tree, and then modify the node, and finally directly to the output


Code attached to the document:[Python] View Plain copy print? #!/usr/bin/python   # -*- coding=utf-8 -*-   # author :  wklken@yeah.net   # date: 2012-05-25   # version: 0.1       from xml.etree.elementtree import elementtree,element      def  Read_xml (In_path):        "" Read and parse XML files           in_path: xml path          return: elementtree ' "        tree = elementtree ()         Tree.parse (In_path)        return tree      Def write_ XML (Tree, out_path):        ' "" Write XML file           tree: xml Tree          out_path:  write path '        tree.write (out_path, encoding= "Utf-8", Xml_declaration=true)       Def if_match (node, kv_map):        "" to determine whether a node contains all incoming parameter properties          node:  node           kv_map:  attribute and attribute value of Map ' '        for key in kv_map:           if node.get (Key)  != kv_map.get (key):                return False       return True      #---------------search -----      def find_nodes (tree, path):        "" To find all nodes that match a path          tree: xml Tree          path:   Node path ''        return tree.findall (path)          def  get_node_by_keyvalue (nodelist, kv_map):        "' locates nodes according to attributes and attribute values, Back to Node          nodelist:  node list           kv_map:  matching attributes and attribute values map '        result_nodes = []        for node in nodelist:            if if_match (node, kv_map):                result_nodes.append (node)        return result_ nodes      #---------------change -----      Def change_node_ Properties (nodelist, kv_map, is_delete=false):        ' Modify/Add  / Delete   node's genusSex and attribute values          nodelist:  node list           kv_map: Attributes and property values map '        for node in nodelist:            for key in kv_map:                if is_delete:                     if key in  node.attrib:                        del node.attrib[key]                else:                    node.set (Key, kv_map.get (key))                    Def change_node_text (Nodelist, text, is_add =false, is_delete=false):        "' Change/Add/delete text       for a node     nodelist: Node list          text :  updated text ' '        for node in nodelist:            if is_add:                node.text += text           elif  is_delete:               node.text  =  ""            else:                node.text = text                   Def create_node (tag, property_map,  Content):        ' ' new node          tag: Node tags          property_map: Attributes and property values map          content:  node closed label text content          return  new node '         element = element (tag, property_map)         element.text = content       return element               Def add_child_node (nodelist,  Element):        "' Add child nodes to a node           nodelist:  Node List          element:  sub node '         for node in nodelist:           node.append ( Element)               Def del_node_by_ Tagkeyvalue (nodelist, tag, kv_map):        ' "" to locate a node and remove it from the same property and property values          nodelist:  parent Node list           tag: Sub-node tags          kv_map:  attributes and attribute values list '         for parent_node in nodelist:            children = parent_node.getchildren ()             for child in children:                if child.tag == tag and if_match (Child, kv_map):    &NBSP;&NBSP;&NBSP;&NBSP;            parent_node.remove (Child)                                       if __name__ ==  "_ _main__ ":               #1 .  read XML file        tree = read_xml ("./test.xml")                 #2 .  Property modification           #A .  Find parent node        nodes = find_nodes (tree,  "Processers/processer")            #B .  to locate child nodes accurately via attributes        result_nodes  = get_node_by_keyvalue (nodes, {"name": "Bprocesser"})            #C .  Modify NodesProperties        change_node_properties (result_nodes, {"Age":  "1"})           #D .  Delete node properties        change_node_properties ( result_nodes, {"value": "}, true"                 #3 .  node modification           #A. New node         A = create_node ("Person",  {"age": "The", "money": "200000"},  "this is the  Firest content ")           #B. Insert under parent node         add_child_node (result_nodes, a)                 #4 .  Delete node            #定位父节点         del_parent_nodes = find_nodes (tree,  "Processers/services/service")             #准确定位子节点并删除之        target_del_node = del_node _by_tagkeyvalue (del_parent_nodes,  "Chain",  {"sequency"  :  "Chain1"})                 #5 .  Modify node text             #定位节点        text_nodes = get_node_by_keyvalue (find_ Nodes (tree,  "Processers/services/service/chain"),  {"sequency": "Chain3"})         change_node_text (text_nodes,  "New text")                #6 .  Output to the result file        write_xml (tree,  "./out.xml")              

Result file after main processing: [HTML] view plain copy print? <?xml version= ' 1.0 ' encoding= ' utf-8 '?> <framework> <processers> <processer file= ' Li  B64/a.so "Name=" Aprocesser "path="/tmp "> </processer> <processer age=" 1 "file=" lib64/b.so " Name= "Bprocesser" > <person age= "money=" 200000 ">this is the Firest content</person>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.