2

I would like to add attribute to a lxml Element like this

<outer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Header>
    <field1 name="blah">some value1</field1>
    <field2 name="asdfasd">some value2</field2>
  </Header>
</outer>

Here is what I have

E = lxml.builder.ElementMaker()    
outer = E.outer
header = E.Header
FIELD1 = E.field1
FIELD2 = E.field2

the_doc = outer(
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance",
    XML_2_HEADER(
        FIELD1('some value1', name='blah'),
        FIELD2('some value2', name='asdfasd'),
        ),
    )

seems like this line is causing some problem

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance",

even if I replace it with

'xmlns:xsi'="http://www.w3.org/2001/XMLSchema-instance",

it won't work.

What is a way to add attribute to lxml Element?

1 Answer 1

4

That's a namespace definition, not an ordinary XML attribute. You can pass namespace information to ElementMaker() as a dictionary, for example :

from lxml import etree as ET
import lxml.builder

nsdef = {'xsi':'http://www.w3.org/2001/XMLSchema-instance'}
E = lxml.builder.ElementMaker(nsmap=nsdef)
doc = E.outer(
    E.Header(
        E.field1('some value1', name='blah'),
        E.field2('some value2', name='asdfasd'),
        ),
    )
print ET.tostring(doc, pretty_print=True)

output :

<outer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Header>
    <field1 name="blah">some value1</field1>
    <field2 name="asdfasd">some value2</field2>
  </Header>
</outer>

Link to the docs: http://lxml.de/api/lxml.builder.ElementMaker-class.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.