XML generation Python reading from DB
<p>I have generate an xml, that take a param value from the model. </p>

<p>The result xml should be like this <code>&lt;read&gt;&lt;test&gt;&lt;value string/&gt;&lt;/test&gt;&lt;/read&gt;</code></p>

<pre><code>root = etree.Element('read')
node = etree.Element('test')
value = etree.SubElement(node, "value" )
for dict in Listing.objects.values('string'):
    value.text = dict['string']
</code></pre>

<p>I get like this :<code>&lt;read&gt;&lt;test&gt;&lt;value&gt;string&lt;/value&gt;&lt;/test&gt;&lt;/read&gt;</code></p>

<p>How should I add the string to the value tag rather than as a TEXT?</p>

<p>Firstly, as @parfait mentioned, the XML result you want (<code>&lt;read&gt;&lt;test&gt;&lt;value string/&gt;&lt;/test&gt;&lt;/read&gt;</code>) is not valid XML.</p>

<p>Using the code you provided, the node <code>test</code> doesn't get added to the root node <code>read</code>.</p>

<h1>1. Code to get your current result:</h1>

<p>If you want something like this as the result: <code>&lt;read&gt;&lt;test&gt;&lt;value&gt;string&lt;/value&gt;&lt;/test&gt;&lt;/read&gt;</code> (which you said you don't), then the code for it would be:</p>

<pre><code>&gt;&gt;&gt; root = etree.Element('read')
&gt;&gt;&gt; node = etree.SubElement(root, 'test')    # `node` should be a `SubElement` of root
&gt;&gt;&gt; # or create as `Element` and use `root.append(node)` to make it a `SubElement` later
... value = etree.SubElement(node, 'value')
&gt;&gt;&gt; value.text = 'string'  # or populate based on your `Listing.objects`
&gt;&gt;&gt; etree.dump(root)
&lt;read&gt;&lt;test&gt;&lt;value&gt;string&lt;/value&gt;&lt;/test&gt;&lt;/read&gt;
</code></pre>

<h1>2. "string" as a value (<em>text</em>) of "test":</h1>

<p>If you want 'string' to be the value of <code>test</code> and not as a <em>node</em> 'value' under 'test', then you should set 'string' as the <code>.text</code> attribute of 'test':</p>

<pre><code>&gt;&gt;&gt; root = etree.Element('read')
&gt;&gt;&gt; node = etree.SubElement(root, 'test')
&gt;&gt;&gt; node.text = 'string'
&gt;&gt;&gt; etree.dump(root)
&lt;read&gt;&lt;test&gt;string&lt;/test&gt;&lt;/read&gt;
</code></pre>

<h1>3. "value" as an <em>attribute</em> of "test" with the <em>value</em> "string":</h1>

<p>The one I <em>think</em> you're trying to get:</p>

<pre><code>&gt;&gt;&gt; root = etree.Element('read')
&gt;&gt;&gt; node = etree.SubElement(root, 'test')
&gt;&gt;&gt; node.attrib    # the current attributes of the node, nothing, empty dict
{}
&gt;&gt;&gt; node.attrib['value'] = 'string'    # this is how you set an attribute
&gt;&gt;&gt; etree.dump(root)
&lt;read&gt;&lt;test value="string" /&gt;&lt;/read&gt;
</code></pre>

<p>Btw, in XML <em>good-ness</em>, the 2nd option is nicer than the 3rd; but botha/all are valid XML.</p>

python xml