FileUtils.py 1.6 KB

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