Python:为什么会出现这个错误? [英] Python: Why this error is coming?

查看:43
本文介绍了Python:为什么会出现这个错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考这个问题:Python:在 xml 中,如何删除父节点内的节点

谁能解释我为什么在我的 python 脚本中遇到这个问题.

Can anyone explain me why I'm facing this issue in my python script.

Value Error : list.remove(x): x not in list

代码如下.

import xml.etree.cElementTree as ET

try:
   tree = ET.parse('Test.xml')
   root = tree.getroot()
   keeper_data = ['06354237', '87654321']
   instances = root.findall('./Replication/Instance')
   for instance in instances:
       data = instance.find('./DataSet/Data')
       if data.text not in keeper_data:
          root.remove(instance)

tree.write('New.xml')

except ValueError as err:
     print ('Value Error : ' + str(err))

下面的xml示例.请注意xml结构与上一个问题的唯一区别是添加了包含所有标签的复制"标签.

xml sample below.Please note the only difference in xml structure from previous question is the addition of "Replication" tag which encloses all the tags.

<?xml version='1.0' encoding='UTF-8'?>
<Root>
<Identification>
   <Description ID="12">Some text</Description>
</Identification>
<Symbols>
  <Name Width="1">abc</Name>
  <Name Width="2">def</Name>
</Symbols>
<Replication  iRowRef="884">
   <Instance RowRef="A">
      <DataSet>
          <Data>12345678</Data>
      </DataSet>
      <DataSet>
          <Data>abcd</Data>
      </DataSet>
      <DataSet>
          <Data>abcd</Data>
      </DataSet>
   </Instance>
   <Instance RowRef="B">
      <DataSet>
         <Data>87654321</Data>
      </DataSet>
      <DataSet>
         <Data>abcd</Data>
      </DataSet>
      <DataSet>
         <Data>abcd</Data>
      </DataSet>
   </Instance>
   <Instance RowRef="C">
      <DataSet>
         <Data>06354237</Data>
      </DataSet>
      <DataSet>
         <Data>abcd</Data>
      </DataSet>
      <DataSet>
         <Data>abcd</Data>
      </DataSet>
  </Instance>
</Replication>
</Root>

推荐答案

您需要使用直接节点,而不是根节点使用Element.remove.

You need to use direct parent node, instead of the root node to use Element.remove.

我在这里使用了 lxml ,因为 ElementTree 没有提供获取父级的方法节点.

I used lxml here, because ElementTree does not provide a method to get a parent node.

import lxml.etree as ET

tree = ET.parse('Test.xml')
root = tree.getroot()
keeper_data = ['06354237', '87654321']
instances = root.findall('./Replication/Instance')
for instance in instances:
    data = instance.find('./DataSet/Data')
    if data.text not in keeper_data:
        instance.getparent().remove(instance)
...

这篇关于Python:为什么会出现这个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆