3

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.

1 Answer 1

6

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 
Sign up to request clarification or add additional context in comments.

1 Comment

I can't comment to Martijn's answer so I wrote as an answer. def func(count): result = [] for i in xrange(count): result.append(E("p", "text", key="value")) return result Not worked for me, but changing result = [] into result = list() did the trick.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.