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

yipeiwu_com5年前Python基础

实例如下所示:

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文件添加字节属性的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中的延迟绑定原理详解

直接看下面例子 my_ld = [lambda x:x*i for i in range(3)] my_list = [ld(2) for ld in my_ld] print(my...

python3监控CentOS磁盘空间脚本

Python脚本监控CentOS磁盘空间,任何一个分区空间使用大于80%即发邮件给到指定邮箱。 monitor.py #-*- coding: utf-8 -*- import s...

利用Pycharm断点调试Python程序的方法

利用Pycharm断点调试Python程序的方法

1.代码 准备没有语法错误的Python程序: #!/usr/bin/python import numpy as np class Network: def __init__(...

基于python(urlparse)模板的使用方法总结

一、简介 urlparse模块用户将url解析为6个组件,并以元组形式返回,返回的6个部分,分别是:scheme(协议)、netloc(网络位置)、path(路径)、params(路径段...

对pyqt5多线程正确的开启姿势详解

如下所示: # -*- coding: utf-8 -*- import sys from PyQt5.QtCore import QThread, pyqtSignal fro...