0

I have generate an xml, that take a param value from the model.

The result xml should be like this <read><test><value string/></test></read>

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

I get like this :<read><test><value>string</value></test></read>

How should I add the string to the value tag rather than as a TEXT?

Parfait
  • 104,375
  • 17
  • 94
  • 125
sipra287
  • 15
  • 4
  • 1
    Your desired result is not a well-formed XML. According to the [w3c rules spec rules for names and tokens](https://www.w3.org/TR/2008/REC-xml-20081126/#NT-NameChar), space cannot be used inside element names See this [SO answer](http://stackoverflow.com/a/3481004/1422451). – Parfait Sep 20 '16 at 20:27
  • The closest sensible XML to the one you want may be ``, see my answer below. – aneroid Sep 21 '16 at 05:32

1 Answers1

0

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.

aneroid
  • 12,983
  • 3
  • 36
  • 66