![](/img/trans.png)
[英]Parsing a XML in Python using ElementTree with repeat elements
[英]Add additional Elements to xml structure using python ElementTree
我正在尝试从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)
不幸的是,根据最后一次迭代,我得到的是在所有附加实例中都具有相同的值。
<?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>
你能告诉我我在做什么错吗?
经过一番研究,我意识到我只是一遍又一遍地复制同一实例(因此,当我在一个实例中设置字段时,它适用于所有重复项)。
为了获得实例副本而不是副本,我使用了copy.deepcopy()方法,如下面的代码片段所示:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.