Python Forum
using lxml to create a complex type element - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Web Scraping & Web Development (https://python-forum.io/forum-13.html)
+--- Thread: using lxml to create a complex type element (/thread-33158.html)



using lxml to create a complex type element - piscvau - Apr-03-2021

Hello
I need to create an xml document from existing python classes and the generated xml document must be compliant with an XML schema.
I am not familiar with lxml nor with ElementTree in python!..
I have gone throught the documentation and cannot find out how to incorporate a complex type element in the tree.

Here is an exercise python code which I use as an exercise.
from lxml import etree


class Model:

    def __init__(self, name, piecesdict):
        self.name = name
        self.piecesdic = piecesdict

    def to_XML(self):
        root = etree.Element("model")
        for key, piece in self.piecesdic.items():
            piecelement = piece.to_XML(root)
            root.append(piecelement)
        return root


class Piece:
    def __init__(self, name, rows):
        self.name = name
        self.rows = rows

    def to_XML(self, father):
        element = etree.SubElement(father, 'piece', {'name': self.name, 'rows': str(self.rows)})
        return element


piece1 = Piece('manche', 54)
piece2 = Piece('devant', 30)
dict = {piece.name: piece for piece in (piece1, piece2)}
mymodel = Model('mymodel', dict)

xml = mymodel.to_XML()
print(etree.tostring(xml, pretty_print=True))
This produces an xml document but the piece element is not a complex type as required in the XML schema.
Any Help would be welcomed.