服务器之家

服务器之家 > 正文

Python Xml文件添加字节属性的方法

时间:2021-01-26 00:13     来源/作者:风吹群起PP凉

实例如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from xml.etree.cElementTree import ElementTree,Element
import xlrd
import re
def read_xlsx(xlsx_path):
  workbook = xlrd.open_workbook(xlsx_path)
  booksheet = workbook.sheet_by_name("Sheet1")
  p = list()
  row_data = []
  for row in range(booksheet.nrows):
    for col in range(booksheet.ncols):
      cel = booksheet.cell(row, col)
      val = cel.value
      try:
        val = cel.value
        val = re.sub(r'\s+', '', val)
      except:
        pass
      if type(val) == float:
        val = int(val)
      else:
        val = str(val)
      row_data.append(val)
  p.append(row_data)
  return p
def read_xml(Int_path):
  tree = ElementTree()
  tree.parse(Int_path)
  return tree
def write_xml(tree, out_path):
  tree.write(out_path,encoding="utf-8",xml_declaration=True)
  '''tree.write('output.xml')'''
def if_match(node,k_name,k_val):
  c = node.get(k_name)
  if node.get(k_name) == k_val:
    return True
  return False
def find_nodes(tree,path):
  return tree.findall(path)
def get_node_by_keyvalue(nodelist,key_name,key_val):
  result_nodes=[]
  for node in nodelist:
    if if_match(node,key_name,key_val):
      result_nodes.append(node)
  return result_nodes
def add_node_properties(nodelist,add_key,add_properties):
  for node in nodelist:
    node.set(add_key,add_properties)
  return node
if __name__ == "__main__":
  tree = read_xml("./ContentList.xml")
  nodes = find_nodes(tree,"Content")
  P = read_xlsx("./ServiceId.xlsx")
  a = P[0]
  i = 0
  while i < 80:
    result_nodes = get_node_by_keyvalue(nodes , "AssetId" , a[i])
    add_node_properties(result_nodes,"ServiceId",a[i+1])
    i = i + 2
  write_xml(tree,'./ContentList1.xml')

以上这篇Python Xml文件添加字节属性的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/NicoleZhang2012/article/details/73650255

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
返回顶部