如何在Python中使用xml.etree.ElementTree生成的xml的同一标记内添加多个值?

时间:2016-01-06 05:53:00

标签: python xml

我正在 Python 中使用 xml.etree.ElementTree 生成 XML文件

有一个标签,我必须通过迭代for循环来添加多个值。

目前只有单个值被添加到该标记。此标记将显示我使用 import wmi 在系统上安装的所有软件的信息。

脚本如下:

    ##Here starts populating elements inside xml file
    top = Element('my_practice_document')
    comment = Comment('details')
    top.append(comment)
    child = SubElement(top, 'my_information')
    childs = SubElement(child,'my_name')
    childs.text = str(options.my_name)
    child = SubElement(top, 'sys_info')

    #Following section is for retrieving list of software installed on the system
    import wmi
    w = wmi.WMI()
    for p in w.Win32_Product():
        if (p.Version is not None) and (p.Caption is not None):
            print p.Caption + " version "+ p.Version      
           child.text =  p.Caption + " version "+ p.Version 

因此,在上面的脚本中,您可以查看检索系统上安装的软件列表的部分。

标签sys_info应该已经安装了软件的所有细节,xml应该如下所示:

    <?xml version="1.0" ?>
    <my_document>
      <my_information>
        <my_name>False</my_name>
      </my_information>
      <sys_info>microsoft office version 123</sys_info>
      <sys_info>skype version 12.0.30723</sys_info>
      ..
      ..
      ..
      ..
    </my_document>

那么,请建议我如何让sys_info标签包含所安装的系统软件的所有细节?

1 个答案:

答案 0 :(得分:0)

尝试将用于创建新<sys_info>元素的逻辑移动到for循环体中:

import wmi
w = wmi.WMI()
for p in w.Win32_Product():
    if (p.Version is not None) and (p.Caption is not None):
        child = SubElement(top, 'sys_info') 
        child.text =  p.Caption + " version "+ p.Version