需求
在实际应用中,需要对xml配置文件进行实时修改,
1.增加、删除 某些节点
2.增加,删除,修改某个节点下的某些属性
3.增加,删除,修改某些节点的文本
使用xml文档
<?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>
实现思想
使用ElementTree,先将文件读入,解析成树,之后,根据路径,可以定位到树的每个节点,再对节点进行修改,最后直接将其输出
实现代码
#!/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): '''读取并解析xml文件 in_path: xml路径 return: ElementTree''' tree = ElementTree() tree.parse(in_path) return tree def write_xml(tree, out_path): '''将xml文件写出 tree: xml树 out_path: 写出路径''' tree.write(out_path, encoding="utf-8",xml_declaration=True) def if_match(node, kv_map): '''判断某个节点是否包含所有传入参数属性 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): '''查找某个路径匹配的所有节点 tree: xml树 path: 节点路径''' return tree.findall(path) def get_node_by_keyvalue(nodelist, kv_map): '''根据属性及属性值定位符合的节点,返回节点 nodelist: 节点列表 kv_map: 匹配属性及属性值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): '''修改/增加 /删除 节点的属性及属性值 nodelist: 节点列表 kv_map:属性及属性值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): '''改变/增加/删除一个节点的文本 nodelist:节点列表 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): '''新造一个节点 tag:节点标签 property_map:属性及属性值map content: 节点闭合标签里的文本内容 return 新节点''' element = Element(tag, property_map) element.text = content return element def add_child_node(nodelist, element): '''给一个节点添加子节点 nodelist: 节点列表 element: 子节点''' for node in nodelist: node.append(element) def del_node_by_tagkeyvalue(nodelist, tag, kv_map): '''同过属性及属性值定位一个节点,并删除之 nodelist: 父节点列表 tag:子节点标签 kv_map: 属性及属性值列表''' 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. 读取xml文件 tree = read_xml("./test.xml") #2. 属性修改 #A. 找到父节点 nodes = find_nodes(tree, "processers/processer") #B. 通过属性准确定位子节点 result_nodes = get_node_by_keyvalue(nodes, {"name":"BProcesser"}) #C. 修改节点属性 change_node_properties(result_nodes, {"age": "1"}) #D. 删除节点属性 change_node_properties(result_nodes, {"value":""}, True) #3. 节点修改 #A.新建节点 a = create_node("person", {"age":"15","money":"200000"}, "this is the firest content") #B.插入到父节点之下 add_child_node(result_nodes, a) #4. 删除节点 #定位父节点 del_parent_nodes = find_nodes(tree, "processers/services/service") #准确定位子节点并删除之 target_del_node = del_node_by_tagkeyvalue(del_parent_nodes, "chain", {"sequency" : "chain1"}) #5. 修改节点文本 #定位节点 text_nodes = get_node_by_keyvalue(find_nodes(tree, "processers/services/service/chain"), {"sequency":"chain3"}) change_node_text(text_nodes, "new text") #6. 输出到结果文件 write_xml(tree, "./out.xml")
修改后的结果
<?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>

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment