Firstly, as @parfait mentioned, the XML result you want (<read><test><value string/></test></read>
) is not valid XML.
Using the code you provided, the node test
doesn't get added to the root node read
.
1. Code to get your current result:
If you want something like this as the result: <read><test><value>string</value></test></read>
(which you said you don't), then the code for it would be:
>>> root = etree.Element('read')
>>> node = etree.SubElement(root, 'test') # `node` should be a `SubElement` of root
>>> # or create as `Element` and use `root.append(node)` to make it a `SubElement` later
... value = etree.SubElement(node, 'value')
>>> value.text = 'string' # or populate based on your `Listing.objects`
>>> etree.dump(root)
<read><test><value>string</value></test></read>
2. "string" as a value (text) of "test":
If you want 'string' to be the value of test
and not as a node 'value' under 'test', then you should set 'string' as the .text
attribute of 'test':
>>> root = etree.Element('read')
>>> node = etree.SubElement(root, 'test')
>>> node.text = 'string'
>>> etree.dump(root)
<read><test>string</test></read>
3. "value" as an attribute of "test" with the value "string":
The one I think you're trying to get:
>>> root = etree.Element('read')
>>> node = etree.SubElement(root, 'test')
>>> node.attrib # the current attributes of the node, nothing, empty dict
{}
>>> node.attrib['value'] = 'string' # this is how you set an attribute
>>> etree.dump(root)
<read><test value="string" /></read>
Btw, in XML good-ness, the 2nd option is nicer than the 3rd; but botha/all are valid XML.