1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- import xml.etree.ElementTree as ElementTree
- import csv
- import os
- def parse_xml(filepath: str):
- """
- Parses an XML File
- It is assumed, that packets are placed on the second hierarchical level and packet-information is encoded
- as attributes
- :param filepath: the path to the XML file to be parsed
- :return: a List of Dictionaries, each Dictionary contains the information of one packet
- """
- tree = ElementTree.parse(filepath)
- root = tree.getroot()
-
- packets = []
- for child in root:
- packets.append(child.attrib)
- return packets
- def parse_csv_to_xml(filepath: str):
- """
- Converts a CSV file into an XML file. Every entry is converted to a child with respective attributes of the
- root node
- :param filepath: the path to the CSV file to be parsed
- :return: a path to the newly created XML file
- """
- filename = os.path.splitext(filepath)[0]
-
- root = ElementTree.Element("trace")
- root.attrib["path"] = filename
-
- with open(filepath, "rt") as csvFile:
- reader = csv.reader(csvFile, delimiter=",")
-
- lineno = -1
- for line in reader:
- lineno += 1
- if not line:
- continue
- packet = ElementTree.SubElement(root, "packet")
- for element in line:
- element = element.replace(" ", "")
- key, value = element.split(":")
- packet.attrib[key] = str(value)
- packet.attrib["LineNumber"] = str(lineno)
-
- tree = ElementTree.ElementTree(root)
- filepath = filename + ".xml"
- tree.write(filepath)
- return filepath
|