FileUtils.py 1.5 KB

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