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

时间:2022-12-05 10:04:55

I am generating XML file using xml.etree.ElementTree in Python.

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

There is one tag in which I have to add multiple values by iterating through a for loop.

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

Currently only single value is getting added to that tag. This tag will display the information of all the software installed on the system which I am getting using import wmi.

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

The script look as follows:

该脚本如下所示:

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

So, in the above script you can have a look in the section where list of software installed on system is retrieved.

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

The tag sys_info should have all details of software installed and the xml should look as follows:

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

So, please suggest how can I have sys_info tag consisting of all the details of system software installed??

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

1 个解决方案

#1


0  

Just try to move the logic for creating new <sys_info> elements into the for loop body :

只是尝试将用于创建新 元素的逻辑移动到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 

#1


0  

Just try to move the logic for creating new <sys_info> elements into the for loop body :

只是尝试将用于创建新 元素的逻辑移动到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