在添加子元素之前或之后创建文档树
我正在使用 lxml 和 Python 来编写 XML 文件。我想知道公认的做法是什么:首先创建文档树,然后添加子元素,或者添加子元素并稍后创建树?我知道这对输出几乎没有任何影响,但我有兴趣从编码风格的角度了解这方面可接受的规范是什么。
示例代码:
page = etree.Element('root')
#first create the tree
doc = etree.ElementTree(page)
#add the subelements
headElt = etree.SubElement(page, 'head')
或者这样:
page = etree.Element('root')
headElt = etree.SubElement(page, 'head')
#create the tree in the end
doc = etree.ElementTree(page)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于树的构造通常是递归操作,因此我想说,一旦子树完成,树根就可以最后创建。但是,我看不出有什么理由比先创建树更好。老实说,我认为这没有公认的规范,我建议您以一种对您和其他可能需要稍后阅读和理解它的人有意义的方式编写代码,而不是试图找到一个规范。
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 sense for you and anyone else that might need to read and understand it later.