专业编程基础技术教程

网站首页 > 基础教程 正文

python比较2个xml内容

ccvgpt 2024-08-05 12:18:25 基础教程 14 ℃
  1. from xml.etree import ElementTree
  2. OK=True
  3. main_pid = 10000
  4. loop_depth = 0
  5. def compare_xml(left, right, key_info='.'):
  6. global loop_depth
  7. loop_depth += 1
  8. if loop_depth == 1: print
  9. if left.tag != right.tag:
  10. print_diff(main_pid, key_info, 'difftag', left.tag, right.tag)
  11. return
  12. if left.text != right.text:
  13. print_diff(main_pid, key_info, 'difftext', left.text, right.text)
  14. return
  15. leftitems = dict(left.items())
  16. rightitems = dict(right.items())
  17. for k,v in leftitems.items():
  18. if k not in rightitems:
  19. s = '%s/%s' % (key_info, left.tag)
  20. print_diff(main_pid, s, 'lostattr', k, "")
  21. for k,v in rightitems.items():
  22. if k not in leftitems:
  23. s = '%s/%s' % (key_info, right.tag)
  24. print_diff(main_pid, s, 'extraattr', "", k)
  25. leftnodes = left.getchildren()
  26. rightnodes = right.getchildren()
  27. leftlen = len(leftnodes)
  28. rightlen = len(rightnodes)
  29. if leftlen != rightlen:
  30. s = '%s/%s' % (key_info, right.tag)
  31. print_diff(main_pid, s, 'difflen', leftlen, rightlen)
  32. return
  33. l = leftlen<rightlen and leftlen or rightlen
  34. d = {}
  35. for i in xrange(l):
  36. node=leftnodes[i]
  37. if node.tag not in d:
  38. d[node.tag] = 1
  39. tag = node.tag
  40. else:
  41. tag = node.tag + str(d[node.tag])
  42. d[node.tag] += 1
  43. s = '%s/%s' % (key_info, tag)
  44. compare_xml(leftnodes[i], rightnodes[i], s)
  45. def print_diff(main_pid, key_info, msg, base_type, test_type):
  46. global OK
  47. info = u'[ %-5s ] %s -> %-40s [ %s != %s ]'%(msg.upper(), main_pid, key_info.strip('./'), base_type, test_type)
  48. print info.encode('gbk')
  49. OK = False

调用:


  1. if __name__ == '__main__':
  2. s1 = '''<?xml version="1.0" encoding="UTF-8"?> \
  3. <employees> \
  4. <employee id = '1'> \
  5. <name>linux</name>\
  6. <age>30</age>\
  7. </employee>\
  8. <employee id = '2'> \
  9. <name>windows</name>\
  10. <age>20</age>\
  11. </employee>\
  12. </employees>'''
  13. s2 = '''<?xml version="1.0" encoding="UTF-8"?> \
  14. <employees> \
  15. <employee id = '3'> \
  16. <name>windows</name>\
  17. <age>20</age>\
  18. </employee>\
  19. <employee id = '4'> \
  20. <name>linux</name>\
  21. <age>30</age>\
  22. </employee>\
  23. </employees>'''
  24. lroot = ElementTree.fromstring(s1)
  25. rroot = ElementTree.fromstring(s2)
  26. compare_xml(lroot, rroot)

python比较2个xml内容

Tags:

最近发表
标签列表