我想用"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发布于 2021-04-21 23:48:40
你可以创建一个原始元素的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>https://stackoverflow.com/questions/67198747
复制相似问题