在添加子元素之前或之后创建文档树

发布于 2024-09-01 06:09:10 字数 479 浏览 2 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

玩套路吗 2024-09-08 06:09:10

由于树的构造通常是递归操作,因此我想说,一旦子树完成,树根就可以最后创建。但是,我看不出有什么理由比先创建树更好。老实说,我认为这没有公认的规范,我建议您以一种对您和其他可能需要稍后阅读和理解它的人有意义的方式编写代码,而不是试图找到一个规范。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文