Understanding the arguments for SubElement factory in ElementTree

M

mirandacascade

Can the **extra argument in the SubElement() factory in ElementTree be
used to set the text property? Example:

Want the text associated with the <subroot> tag to be xyz.

<root>
<subroot>xyz</subroot>
</root>

rather than:
root = Element('root')
subroot = SubElement(root, 'subroot')
subroot.text = 'xyz'

Was wondering whether this code accomplish that
root = Element('root')
subroot = SubElement(root, 'subroot', text='xyz')
 
B

B Mahoney

Your SubElement call is lacking the attrib argument, but you can't set
text, anyway.

The elementtree source makes it clear, you can only set element attrib
attributes
with SubElement

def SubElement(parent, tag, attrib={}, **extra):
attrib = attrib.copy()
attrib.update(extra)
element = parent.makeelement(tag, attrib)
parent.append(element)
return element
 
G

Giovanni Bajo

<root>
<subroot>xyz</subroot>
</root>

rather than:
root = Element('root')
subroot = SubElement(root, 'subroot')
subroot.text = 'xyz'

Was wondering whether this code accomplish that
root = Element('root')
subroot = SubElement(root, 'subroot', text='xyz')


No, this creates:

<root>
<subroot text="xyz" />
</root>

I believe the text ought to be set in a separate statement.

Giovanni Bajo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,043
Members
48,769
Latest member
Clifft

Latest Threads

Top