XML生成Python从DB读取

时间:2016-09-20 18:15:11

标签: python xml

我已生成一个xml,它从模型中获取一个参数值。

结果xml应该像这个<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']

我是这样的:<read><test><value>string</value></test></read>

我应该如何将字符串添加到值标记而不是TEXT?

1 个答案:

答案 0 :(得分:0)

首先,正如@parfait所提到的,您想要的XML结果(<read><test><value string/></test></read>)不是有效的XML。

使用您提供的代码,节点test无法添加到根节点read

1。获取当前结果的代码:

如果你想要这样的结果:<read><test><value>string</value></test></read>(你说你不是),那么代码就是:

>>> 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。 &#34;串&#34;作为&#34; test&#34;的值<(em> text ):

如果你想要&#39; string&#39;是test的值,而不是节点&#39;值&#39;在&#39; test&#39;下,你应该设置&#39; string&#39;作为&#39; test&#39;:

.text属性
>>> root = etree.Element('read')
>>> node = etree.SubElement(root, 'test')
>>> node.text = 'string'
>>> etree.dump(root)
<read><test>string</test></read>

3。 &#34;值&#34;作为&#34; test&#34;的属性使用&#34;字符串&#34;:

认为你想要得到的那个:

>>> 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>

顺便说一句,在XML good-ness 中,第二个选项比第三个更好;但是botha / all都是有效的XML。