Python – AD8G https://ad8g.net Adventures in Ham Radio Fri, 18 Nov 2011 23:01:39 +0000 en-US hourly 1 Python: Get XML Representation of an Object https://ad8g.net/python-get-xml-representation-of-an-object/ https://ad8g.net/python-get-xml-representation-of-an-object/#respond Fri, 18 Nov 2011 23:01:39 +0000 https://ad8g.net/2011/11/18/python-get-xml-representation-of-an-object/ I needed to return all the members of an object as an XML document in Python. I used the ElementTree library to do this. The class in question is pretty basic: It has a constructor, member variables, getters and setters for the member variables, and now this new function. Every Python class has a built-in […]

The post Python: Get XML Representation of an Object appeared first on AD8G.

]]>
I needed to return all the members of an object as an XML document in Python. I used the ElementTree library to do this.

The class in question is pretty basic: It has a constructor, member variables, getters and setters for the member variables, and now this new function.

Every Python class has a built-in __dict__ member, which is a dictionary ({}) of key/value pairs for all of the member variables, so I use that to get all of the variables to add to the ElementTree.

This function returns an xml.etree.ElementTree.Element object, which can be turned into a string if needed by using ElementTree’s tostring() method.

def getXML(self):
    """ Returns an XML representation of the object """
    topElem = Element("item")
    for key in self.__dict__.keys():
        elem = SubElement(topElem, key)
        elem.text = str(self.__dict__[key])
    return topElem

The post Python: Get XML Representation of an Object appeared first on AD8G.

]]>
https://ad8g.net/python-get-xml-representation-of-an-object/feed/ 0