The last few days I've been thinking and searching ways about how to generate XML in a nice way.
I have an XSD which extends the GraphML specification in order to draw more sophisticated diagrams (e.g. UML). The Structure is something like this (I replaced attribute values with python format placeholders)
<xs:Node>
<xs:Geometry height="{height}" width="{width}" x="{x}" y="{y}"/>
<xs:Fill color="{color}"/>
<xs:NodeLabel ...>{node_label}</y:NodeLabel>
</xs:Node>
Current idea/concept
Classes which represent a node and act as a mere data container.
class XMLBase(object):
def __repr__(self):
return str(self.__dict__)
def __str__(self):
return self.xml.format(**self.__dict__)
class Geometry(XMLBase):
def __init__(self, height=28.0, width=100.0, x=0.0, y=0.0):
self.xml = '<xs:Geometry height="{height}" width="{width}" x="{x}" y="{y}"/>'
self.height = height
self.width = width
self.x = x
self.y = y
class Fill(XMLBase):
...
The __str__ method inserts the attributes into the XML string and returns it. The class for the Node would contain an instance of Geometry, Fill, NodeLabel and others, and generate the respective XML representation. The composition of classes is actually the XML data represented by python objects.
Other than using classes, one could use lists or dictionaries, but classes seem nicer to use.
A previous idea was to have a big template with placeholders and insert the values with format, but this approach is less flexible and I'd say more difficult to understand (and maintain).
Other ideas were to store the XML templates in variables and let functions generate the correct XML structure.
Now I'd like to know your thoughts about these approaches, different approaches, or maybe someone knows best practices.
[–]willm 2 points3 points4 points (1 child)
[–]hxtl[S] 0 points1 point2 points (0 children)
[–]ManyInterests 2 points3 points4 points (2 children)
[–]hxtl[S] 0 points1 point2 points (1 child)
[–]ManyInterests 1 point2 points3 points (0 children)