使用ElementTree移除MARC XML中955字段时遇ValueError错误
问题:移除MARC XML中955字段时触发ValueError错误
我有一个包含两条记录的MARC XML文件,想要移除其中的955 datafield字段。使用xml.etree.ElementTree的findall遍历目标字段,尝试用root.remove()删除时,出现了ValueError: list.remove(x): x not in list错误,参考ElementTree官方示例后仍未解决问题。
相关代码
import xml.etree.ElementTree as ET tree = ET.parse('toggle.xml') root = tree.getroot() for a955 in root.findall('record/datafield[@tag="955"]'): root.remove(a955)
报错信息
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[1], line 6 3 root = tree.getroot() 5 for a955 in root.findall('record/datafield[@tag="955"]'): ----> 6 root.remove(a955) ValueError: list.remove(x): x not in list
XML示例
<collection> <record> <leader>00859cam a2200277Ia 4500</leader> <controlfield tag="005">20170510144913.0</controlfield> <controlfield tag="008">880930s1983 enka 00010 eng d</controlfield> <datafield tag="035" ind1=" " ind2=" "> <subfield code="a">ocm13279646 880930</subfield> </datafield> ...(省略部分字段) <datafield tag="955" ind1=" " ind2=" "> <subfield code="a">QP4.88.1745</subfield> <subfield code="b">QP4DOT88DOT</subfield> </datafield> </record> <record> ...(省略部分字段) <datafield tag="955" ind1=" " ind2=" "> <subfield code="y">2020</subfield> <subfield code="b">V000258858</subfield> </datafield> </record> </collection>
参考的官方示例
for country in root.findall('country'): # using root.findall() to avoid removal during traversal rank = int(country.find('rank').text) if rank > 50: root.remove(country)
解决方案
问题核心是调用remove()的对象错误:a955元素是<record>的直接子节点,而非root(即<collection>)的子节点。ElementTree的remove()方法只能删除调用者的直接子元素,因此直接用root.remove(a955)会触发错误。
正确的做法是逐层遍历,先找到每个<record>节点,再在其内部删除对应的955字段:
import xml.etree.ElementTree as ET tree = ET.parse('toggle.xml') root = tree.getroot() # 遍历所有record节点 for record in root.findall('record'): # 在当前record下查找并删除所有955字段 for a955 in record.findall('datafield[@tag="955"]'): record.remove(a955) # 保存修改后的XML文件 tree.write('modified_toggle.xml', encoding='utf-8', xml_declaration=True)
内容的提问来源于stack exchange,提问作者Mike Saunders
相关产品推荐
相关产品推荐

