FileUtils.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import xml.etree.ElementTree as ElementTree
  2. import csv
  3. import os
  4. def parse_xml(filepath: str):
  5. """
  6. Parses an XML File
  7. It is assumed, that packets are placed on the second hierarchical level and packet-information is encoded
  8. as attributes
  9. :param filepath: the path to the XML file to be parsed
  10. :return: a List of Dictionaries, each Dictionary contains the information of one packet
  11. """
  12. tree = ElementTree.parse(filepath)
  13. root = tree.getroot()
  14. # Convert Tree to List of Dictionaries
  15. packets = []
  16. for child in root:
  17. packets.append(child.attrib)
  18. return packets
  19. def parse_csv_to_xml(filepath: str):
  20. """
  21. Converts a CSV file into an XML file. Every entry is converted to a child with respective attributes of the
  22. root node
  23. :param filepath: the path to the CSV file to be parsed
  24. :return: a path to the newly created XML file
  25. """
  26. filename = os.path.splitext(filepath)[0]
  27. # build a tree structure
  28. root = ElementTree.Element("trace")
  29. root.attrib["path"] = filename
  30. # parse the csvFile into reader
  31. with open(filepath, "rt") as csvFile:
  32. reader = csv.reader(csvFile, delimiter=",")
  33. # loop through the parsed file, creating packet-elements with the structure of the csvFile as attributes
  34. lineno = -1 # lines start at zero
  35. for line in reader:
  36. lineno += 1
  37. if not line:
  38. continue
  39. packet = ElementTree.SubElement(root, "packet")
  40. for element in line:
  41. element = element.replace(" ", "")
  42. key, value = element.split(":")
  43. packet.attrib[key] = str(value)
  44. packet.attrib["LineNumber"] = str(lineno)
  45. # writing the ElementTree into the .xml file
  46. tree = ElementTree.ElementTree(root)
  47. filepath = filename + ".xml"
  48. tree.write(filepath)
  49. return filepath