【问题标题】:Creating xml dynamically with lxml使用 lxml 动态创建 xml
【发布时间】:2012-10-17 09:58:57
【问题描述】:

我没有使用 lxml 来创建 xml,所以我有点迷茫。我可以创建一个函数,创建一个元素:

from lxml import etree as ET    
from lxml.builder import E

In [17]: def func():
    ...:     return E("p", "text", key="value")

In [18]: page = (
    ...:     E.xml(
    ...:         E.head(
    ...:             E.title("This is a sample document")
    ...:         ),
    ...:         E.body(
    ...:             func()
    ...:             
    ...:         )
    ...:     )
    ...: )

In [19]: print ET.tostring(page,pretty_print=True)
<xml>
  <head>
    <title>This is a sample document</title>
  </head>
  <body>
    <p key="value">text</p>
  </body>
</xml>

如何使函数添加多个元素?例如,我想func(3) 创建 3 个新段落。如果 func 重新生成一个列表,我会得到一个 TypeError。

【问题讨论】:

    标签: python xml lxml


    【解决方案1】:

    如果您的函数可以返回多个元素,那么您需要使用* argument syntax 将这些元素作为位置参数传递给E.body() 方法:

    ...
        E.body(
            *func()
        )
    

    现在func() 应该返回一个序列:

    def func(count):
        result = []
        for i in xrange(count):
            result.append(E("p", "text", key="value"))
        return result
    

    【讨论】:

    • 我无法评论 Martijn 的回答,所以我写了一个答案。 def func(count): result = [] for i in xrange(count): result.append(E("p", "text", key="value")) return result 对我不起作用,但改变 result = [] 变成 result = list() 成功了。
    猜你喜欢
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 2011-10-02
    • 1970-01-01
    • 2021-08-30
    相关资源
    最近更新 更多