Detailed explanation of the method for parsing and modifying XML content in the Python program, pythonxml

Source: Internet
Author: User

Detailed explanation of the method for parsing and modifying XML content in the Python program, pythonxml

Requirement
In actual applications, You need to modify the xml configuration file in real time,

1. add or delete some nodes

2. add, delete, and modify certain attributes of a node

3. add, delete, and modify the text of some nodes.

Use xml documents

<?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>      <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>

Implementation idea
Use ElementTree to read the file and parse it into a tree. Then, you can locate each node in the tree based on the path, modify the node, and then output it directly.

Implementation Code

#! /Usr/bin/python #-*-coding = UTF-8-*-# author: wklken@yeah.net # date: 2012-05-25 # version: 0.1 from xml. etree. elementTree import ElementTree, Elementdef read_xml (in_path): ''' read and parse the xml file in_path: xml Path return: ElementTree ''' tree = ElementTree () tree. parse (in_path) return treedef write_xml (tree, out_path): ''' write the xml file into the tree: xml tree out_path: Write path ''' tree. write (out_path, encoding = "UTF-8", xml_declaration = True) def if_match (node, kv_map): ''' determines whether a node contains all input parameter attributes node: node kv_map: map ''' for key in kv_map: if node. get (key )! = Kv_map.get (key): return False return True # --------------- search ----- def find_nodes (tree, path): ''' find all node trees matching a path: xml tree path: node path '''return tree. findall (path) def get_node_by_keyvalue (nodelist, kv_map): ''' locate the matched Node Based on the attribute and attribute value, and return the node nodelist: node list kv_map: matching attributes and attribute values map ''' result_nodes = [] for node in nodelist: if if_match (node, kv_map): equals (node) return result_nodes # ------------- change ----- def change_node_properties (nodelist, kv_map, is_delete = False): ''' Modify/Add/delete node attributes and attribute values: nodelist: node list kv_map: attribute and attribute value 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 a node's text nodelist: node list text: the updated text ''' for node in nodelist: if is_add: node. text + = text elif is_delete: node. text = "" else: node. text = textdef create_node (tag, property_map, content): ''' create a new node tag: node tag property_map: attribute and attribute value map content: return the text content in the closed node label. The new node '''element = element (tag, property_map) Element. text = content return elementdef add_child_node (nodelist, element): ''' Add a subnode to a node. nodelist: node list element: subnode ''' for node in nodelist: node. append (element) def del_node_by_tagkeyvalue (nodelist, tag, kv_map): ''' locates a node based on attributes and attribute values, and deletes the nodelist: parent node list tag: child node label kv_map: attribute and Attribute Value List ''' for parent_node in nodelist: children = parent_node.getchildren () for child in children: if child. tag = tag and if_match (child, kv_map): parent_node.remove (child) if _ name _ = "_ main _": #1. read xml file tree = read_xml (". /test. xml ") #2. attribute Modification #. find the parent node nodes = find_nodes (tree, "processers/processer") # B. accurately locate the subnode result_nodes = get_node_by_keyvalue (nodes, {"name": "BProcesser"}) # C. modify node attributes change_node_properties (result_nodes, {"age": "1"}) # D. delete node attributes change_node_properties (result_nodes, {"value": ""}, True) #3. node modification #. create node a = create_node ("person", {"age": "15", "money": "200000"}, "this is the firest content") # B. insert to the parent node add_child_node (result_nodes, a) #4. delete a node # locate the parent node del_parent_nodes = find_nodes (tree, "processers/services/service") # accurately locate the child node and delete the target_del_node = del_node_by_tagkeyvalue (del_parent_nodes, "chain ", {"sequency": "chain1"}) #5. modify the node text # locate the node 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 ")

Modified result

<?xml version='1.0' encoding='utf-8'?><framework>  <processers>    <processer file="lib64/A.so" name="AProcesser" path="/tmp">    </processer>    <processer age="1" file="lib64/B.so" name="BProcesser">      <person age="15" money="200000">this is the firest content</person>    </processer>    <processer age="1" file="lib64/B.so2222222" name="BProcesser">      <person age="15" money="200000">this is the firest content</person>    </processer>    <services>      <service name="search" output_formatter="OutPutFormatter:service_inc"        prefix="/bin/search?">        <chain sequency="chain2" />      </service>      <service name="update" prefix="/bin/update?">        <chain sequency="chain3" value="fordelete">new text</chain>      </service>    </services>  </processers></framework>

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.