如何解决.xml 文件中元素属性的小问题Python
我想用“cooling cid=2”元素替换“cooling cid=1”元素。因此,我使用 myroot[0][0]=myroot[0][1]
进行了修改,但是当我想用“cid=1”替换第一个“cid”值时,它也会更改第二个元素上的 cid 值。
我也想删除 <cooling cid="2">
但它不适用于 myroot.remove(myroot[0][1])
我怎样才能做到这一点?
输入:
<compositionhistory type="result" iteration="1">
<compositiondata tid="6">
<cooling cid="1">
<isotope zamid="10010">3.776028e-09</isotope>
<isotope zamid="30060">2.851899e-09</isotope>
<isotope zamid="30070">2.253752e-10</isotope>
<isotope zamid="30080">7.533722e-18</isotope>
<isotope zamid="30090">1.172801e-18</isotope>
<isotope zamid="40060">6.672459e-39</isotope>
<isotope zamid="40080">1.084507e-33</isotope>
<isotope zamid="40090">8.142463e-11</isotope>
</cooling>
<cooling cid="2">
<isotope zamid="10010">3.776028e-09</isotope>
<isotope zamid="30060">2.851899e-09</isotope>
<isotope zamid="30070">2.253752e-10</isotope>
<isotope zamid="40090">8.142463e-11</isotope>
</cooling>
</compositiondata>
</compositionhistory>
代码:
import xml.etree.ElementTree as ET
mytree = ET.parse('input2.xml') #open file
myroot = mytree.getroot()
for child in myroot[0]:
print(child.attrib)
myroot[0][0]=myroot[0][1] # paste "cid2" element on "cid=1"
myroot[0][1].set("cid","1") # here is the problem. I want to rename only the first element and keep cid=2 on the second element
for child in myroot[0]:
print(child.attrib)
mytree.write('output2.xml')
输出:
<compositionhistory iteration="1" type="result">
<compositiondata tid="6">
<cooling cid="1">
<isotope zamid="10010">3.776028e-09</isotope>
<isotope zamid="30060">2.851899e-09</isotope>
<isotope zamid="30070">2.253752e-10</isotope>
<isotope zamid="40090">8.142463e-11</isotope>
</cooling>
<cooling cid="1"> # here it should be cid=2 not cid=1
<isotope zamid="10010">3.776028e-09</isotope>
<isotope zamid="30060">2.851899e-09</isotope>
<isotope zamid="30070">2.253752e-10</isotope>
<isotope zamid="40090">8.142463e-11</isotope>
</cooling>
</compositiondata>
</compositionhistory
解决方法
您可以制作原始元素的 deepcopy
并且它应该可以工作:
import copy
myroot[0][0]=copy.deepcopy(myroot[0][1])
修改只显示在原始元素上:
myroot[0][0].set("cid","1") # I believe you only want to rename the first
打印结果元素:
In [92]: print(ET.tostring(myroot).decode())
<compositionhistory iteration="1" type="result">
<compositiondata tid="6">
<cooling cid="1">
<isotope zamid="10010">3.776028e-09</isotope>
<isotope zamid="30060">2.851899e-09</isotope>
<isotope zamid="30070">2.253752e-10</isotope>
<isotope zamid="40090">8.142463e-11</isotope>
</cooling>
<cooling cid="2">
<isotope zamid="10010">3.776028e-09</isotope>
<isotope zamid="30060">2.851899e-09</isotope>
<isotope zamid="30070">2.253752e-10</isotope>
<isotope zamid="40090">8.142463e-11</isotope>
</cooling>
</compositiondata>
</compositionhistory>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。