How to insert element with text?

50 Views Asked by At

I can insert an element like this:

product_node.insert(cnt, etree.Element("vod_type"))

Is it possible to do the following:

product_node.insert(cnt, etree.Element("vod_type").text="hello")

Or something of the sort. Or do I have to split it up into three lines?

elem = etree.Element("vod_type")
elem.text = "hello"
product_node.insert(cnt, elem)
2

There are 2 best solutions below

0
LMC On BEST ANSWER

ElementMaker could be used to do that in one step

from lxml.builder import E

product_node.insert(cnt, E("vod_type", "hello"))
0
Hermann12 On

I think standard xml.etree can’t assign text directly in one liner, but you can do:

import xml.etree.ElementTree as ET

xml_str = """<root/>"""
root = ET.fromstring(xml_str)

# insert a subelement
b = ET.SubElement(root, 'b')

# Create element and assign text and attribute
c = ET.Element('c', id='2')
c.text = 'some text'
c.set('name', 'attrib value')

# insert on position 
b.insert(0, c) # index, subelement

ET.indent(root, space='  ')
ET.dump(root)

Output:

<root>
  <b>
    <c id="2" name="attrib value">some text</c>
  </b>
</root>

But you can get the same result from string in one line:

# Create element from string
c = ET.fromstring("""<c id="2" name="attrib value">some text</c>""")