开发者

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

开发者 https://www.devze.com 2022-12-31 03:04 出处:网络
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 softwar

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('SecondC开发者_JS百科hild')

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?


The following code works:

def createSubElement(text, tagText = ""):
    elem = etree.SubElement(root, text)
    elem.text = tagText

createSubElement('firstChild', 'first one')
createSubElement('SecondChild', 'second one')

print etree.tostring(root)

Using a class rather than a function has mostly to do with keeping state in the class's instances (in very few use cases will a class make sense if there's no state-keeping required), which has nothing to do with your problem -- as the code shows, your problem was simply that you were not binding any name to the element returned from the SubElement call, and therefore of course you were unable to further manipulate that element (e.g. by setting its text attribute) in the rest of your function.

0

精彩评论

暂无评论...
验证码 换一张
取 消