python 中xml解析有很多种方式,本文采用ElementTree方式对xml进行解析。以下代码是对一个xml文档中具体属性值进行修改的例子(会涉及到遍历xml文本),修改的界面如下:
实际修改的代码如下:
import xml.etree.ElementTree as ET
import json
import os
import sys
data_id = 1
tree = ET.ElementTree()
class XmlEdit:
def __init__(self):
pass
#遍历xml节点
def through_xml_data(self, root_node, level, result_list):
global data_id
temp_list = [data_id, level, root_node.tag, root_node.attrib]
result_list.append(temp_list)
data_id += 1
children_node = root_node.getchildren()
if len(children_node) == 0:
return
for child in children_node:
self.through_xml_data(child, level + 1, result_list)
return
def get_xml_file(self, in_file_path):
if os.path.exists(in_file_path):
print "xml file:" + in_file_path + " exit"
root = ET.parse(in_file_path).getroot()
level = 1
result_list = []
self.through_xml_data(root, level, result_list)
return result_list
else:
print "xml file" + in_file_path + " no exit"
return []
def get_isdbt_same_attr_positon(self, key, result_list):
# layer对应在result_list中的位置
map_dict = {"layer1": 3, "Layer1": 3,
"layer2": 4, "Layer2": 4,
"layer3": 5, &#