Confused as to use a class or a function: Writing XML files using lxml and Python

Posted by PulpFiction on Stack Overflow See other posts from Stack Overflow or by PulpFiction
Published on 2010-05-23T16:33:13Z Indexed on 2010/05/23 17:20 UTC
Read the original article Hit count: 312

Filed under:
|

Hi.

I need to write XML files using lxml and Python.

However, I can't figure out whether to use a class to do this or a function. The point being, this is the first time I am developing a proper software and deciding where and why to use a class still seems mysterious.

I will illustrate my point.

For example, consider the following function based code I wrote for adding a subelement to a etree root.

from lxml import etree

root = etree.Element('document')

def createSubElement(text, tagText = ""):
    etree.SubElement(root, text)
    # How do I do this: element.text = tagText

createSubElement('firstChild')
createSubElement('SecondChild')

As expected, the output of this is:

<document>
  <firstChild/>
  <SecondChild/>
</document>

However as you can notice the comment, I have no idea how to do set the text variable using this approach.

Is using a class the only way to solve this? And if yes, can you give me some pointers on how to achieve this?

© Stack Overflow or respective owner

Related posts about python

Related posts about lxml