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 が発生します。