tags:

views:

33

answers:

1

Hello everyone.

I am using lxml and Python for writing XML files. I was wondering what is the accepted practice: creating a document tree first and then adding the sub elements OR adding the sub elements and creating the tree later? I know this hardly makes any difference as to the output, but I was interested in knowing what is the accepted norm in this from a coding-style point of view.

Sample code:

page = etree.Element('root')
#first create the tree
doc = etree.ElementTree(page) 
#add the subelements
headElt = etree.SubElement(page, 'head')

Or this:

page = etree.Element('root')
headElt = etree.SubElement(page, 'head')
#create the tree in the end
doc = etree.ElementTree(page) 
+1  A: 

Since tree construction is typically a recursive action, I would say that the tree root could get created last, once the subtree is done. However, I don't see any reason why that should be any better than creating the tree first. I honestly don't think there's an accepted norm for this, and rather than trying to find one I would advise you to write your code in such a way that it makes sence for you and anyone else that might need to read and understand it later.

Banang
Thanks for the reply.
PulpFiction