I havent used lxml to create xml, so i am somewhat lost. I can make a function, that creates an elemnt:
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>
How can i make the function to add multiple elements? For example, i would like func(3) to create 3 new paragraphs. If the func reurns a list, i get a TypeError.
If your function can return multiple elements, then you need to use the * argument syntax to pass these elements as positional arguments to the E.body() method:
...
E.body(
*func()
)
Now func() should return a sequence:
def func(count):
result = []
for i in xrange(count):
result.append(E("p", "text", key="value"))
return result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With