2

I want to generate the following xml file:

<foo if="bar"/>

I've tried this:

from lxml import etree
etree.Element("foo", if="bar")

But I got this error:

page = etree.Element("configuration", if="ok")
                                       ^
SyntaxError: invalid syntax

Any ideas?

I'm using python 2.7.9 and lxml 3.4.2

3 Answers3

7
etree.Element("foo", {"if": "bar"})

The attributes can be passed in as a dict:

from lxml import etree

root = etree.Element("foo", {"if": "bar"})

print etree.tostring(root, pretty_print=True)

output

<foo if="bar"/>
Leon
  • 12,013
  • 5
  • 36
  • 59
6
etree.Element("foo", **{"if": "bar"})
Zaaferani
  • 951
  • 9
  • 31
-2

'if' is a reserved word in Python, which means that you can't use it as an identifier.

R Hyde
  • 10,301
  • 1
  • 32
  • 28