Python Forum
using lxml to create a complex type element
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
using lxml to create a complex type element
#1
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Check element for a particular type Pavel_47 2 2,202 Jan-13-2021, 04:30 PM
Last Post: Pavel_47

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020