Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating xml dynamically with lxml

Tags:

python

xml

lxml

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.

like image 910
root Avatar asked Mar 16 '26 01:03

root


1 Answers

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
like image 87
Martijn Pieters Avatar answered Mar 18 '26 13:03

Martijn Pieters