3

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) 
4

1 に答える 1

1

ツリーの構築は通常、再帰的なアクションであるため、サブツリーが完了すると、ツリーのルートが最後に作成される可能性があると言えます。ただし、最初にツリーを作成するよりも優れている理由はわかりません。正直なところ、これには受け入れられている規範があるとは思いません。それを見つけようとするよりも、後で読んで理解する必要があるかもしれないあなたや他の人にとって意味のある方法でコードを書くことをお勧めします。 .

于 2010-05-13T10:52:23.690 に答える