【问题标题】:Add additional Elements to xml structure using python ElementTree使用 python ElementTree 将附加元素添加到 xml 结构
【发布时间】:2016-01-20 22:49:53
【问题描述】:

我正在尝试从 xml 格式中取出一条记录,并将其相乘,这样每个新实例都将包含特定字段的不同值。

我认为最好的方法是准备一个包含单个实例(虚拟实例)的骨架 xml 文件(见下文)。然后,我的脚本将指向这个实例,并且对于每个循环迭代,它将用所需的值替换它的字段,并将其附加回 xml 树。

xml文件:

<?xml version="1.0" encoding="utf-8"?>
<ServerData>
<CreationDate>0001-01-01T00:00:00</CreationDate>
<Processes>
   <ProtectedProcess>
       <Name>XXX</Name>
       <Path>XXX</Path>
   </ProtectedProcess>
 </Processes>
</ServerData>

我的代码:

import xml.etree.ElementTree as ET
self.tree = ET.parse(infile)
self.root = self.tree.getroot()

processes    = self.root.find("Processes")    
process_root = self.root.find("Processes").find("ProtectedProcess")

for app in self.apps:
    process_root.find("Name").text = app.lower()
    process_root.find("Path",ns).text = app
    processes.append(process_root)

fd = open("./xxx.xml", "wb")
self.tree.write(fd, encoding='utf-8', xml_declaration=False)

不幸的是,根据上次迭代,我得到的是在所有附加的实例中都具有相同的值。

xxx.xml:

<?xml version="1.0" encoding="utf-8"?>
<ServerData>
<CreationDate>0001-01-01T00:00:00</CreationDate>
<Processes>
   <ProtectedProcess>
       <Name>/applications/safari.app/contents/macos/safari</Name>
       <Path>/Applications/Safari.app/Contents/MacOS/Safari</Path>
   </ProtectedProcess>
   <ProtectedProcess>
       <Name>/applications/safari.app/contents/macos/safari</Name>
       <Path>/Applications/Safari.app/Contents/MacOS/Safari</Path>
   </ProtectedProcess>
   <ProtectedProcess>
       <Name>/applications/safari.app/contents/macos/safari</Name>
       <Path>/Applications/Safari.app/Contents/MacOS/Safari</Path>
   </ProtectedProcess>
 </Processes>
</ServerData>

你能告诉我我做错了什么吗?

【问题讨论】:

    标签: python xml elementtree


    【解决方案1】:

    经过一些研究,我意识到我只是一遍又一遍地复制同一个实例(因此,当我在其中一个实例中设置字段时,它适用于所有重复项)。

    为了获取实例副本而不是副本,我使用了 copy.deepcopy() 方法,如以下代码 sn-p 所示:

    for app in self.apps:
        l=copy.deepcopy(process_root)
        l.find("d3p1:Name",ns).text = lower.app
        l.find("d3p1:Path",ns).text = app
        processes.append(l)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      相关资源
      最近更新 更多