简体   繁体   中英

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

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?

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 (eg by setting its text attribute) in the rest of your function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM