XML generation

This commit is contained in:
Mylloon 2024-04-17 15:33:10 +02:00
parent 6f32e70a5e
commit 5c6e86b82a
Signed by: Anri
GPG key ID: A82D63DFF8D1317F

View file

@ -1,6 +1,9 @@
from csv import reader as csv_reader from csv import reader as csv_reader
from pprint import pp as print, pformat from pprint import pformat
from pprint import pp as pprint
from sys import argv, stderr from sys import argv, stderr
from xml.dom.minidom import parseString as xml_parser
from xml.etree import ElementTree
class System: class System:
@ -48,6 +51,30 @@ class System:
def __repr__(self): def __repr__(self):
return pformat(self.__dict__, compact=True, width=120, sort_dicts=False) return pformat(self.__dict__, compact=True, width=120, sort_dicts=False)
def to_xml(self) -> ElementTree.Element:
"""Convert the current system into an XML element"""
system = ElementTree.Element("lsystem")
base = ElementTree.SubElement(system, "base")
base.text = "".join(self.base)
axiom = ElementTree.SubElement(system, "axiom")
axiom.text = self.axiom
substitutions = ElementTree.SubElement(system, "substitutions")
for member, substitution in self.substitutions:
sub_element = ElementTree.SubElement(substitutions, "substitution")
sub_element.set("member", member)
sub_element.text = substitution
interpretations = ElementTree.SubElement(system, "interpretations")
for member, interpretation in self.interpretations:
inter_element = ElementTree.SubElement(interpretations, "interpretation")
inter_element.set("member", member)
inter_element.text = interpretation
return system
def data_reader(path: str, delimiter: str = ","): def data_reader(path: str, delimiter: str = ","):
"""Read a CSV file and returns a list of L-System""" """Read a CSV file and returns a list of L-System"""
@ -67,11 +94,30 @@ def data_reader(path: str, delimiter: str = ","):
return res return res
def lsystems_xml(systems: list[System]) -> ElementTree.Element:
"""Convert list of L-system structure into XML"""
root = ElementTree.Element("lsystems")
for system in systems:
root.append(system.to_xml())
return root
if __name__ == "__main__": if __name__ == "__main__":
if len(argv) != 2: if len(argv) != 2:
print(f"Syntax error:\n\tpython {argv[0]} file.csv", stream=stderr) pprint(f"Syntax error:\n\tpython {argv[0]} file.csv", stream=stderr)
exit(1) exit(1)
# TODO: Check if we have to dump to stdout or we write into a file
# use `argparse` for cli arguments
# TODO: Pour les arguments, utilisé `argparse` # Read data
lsystems = data_reader(argv[1])
print(data_reader(argv[1])) # Generate XML
xml = lsystems_xml(lsystems)
# Print XML
dom = xml_parser(ElementTree.tostring(xml))
print(dom.toprettyxml(encoding="UTF-8").decode())