根据元素标准从树中删除 xml 个节点

Deleting xml node from tree based on element criteria

我正在使用 XMLs,我正在尝试根据元素的标准删除 <node>。这个想法是删除第二个项目。我试图制作 ITEMS 列表,然后根据该列表将它们从 root lvl 中删除,但我得到了

ValueError "ValueError: list.remove(x): x not in list"

而且我不知道如何获得更高的等级。

代码:

import xml.etree.ElementTree as ET

tree = ET.parse("PW.xml")
root = tree.getroot()

items = root.findall('.//ITEM[PROPERTY]')
m = -1
delate = []
for i in items:
  pl = i.findall('PROPERTY[@NAME="ID detalu"]')
  #print([(pv.attrib['NAME'], pv.text) for pv in pl])
  m = m + 1
  for p in pl:
    if (p.text.startswith('SHP')):
      delate.append(m) 

tree.write('PW.xml')

XML:

<DATA>
    <OBJECT TYPE="Dane">
        <ITEM>
            <PROPERTY NAME="[1]" />
            <PROPERTY NAME="child2">07</PROPERTY>
            <PROPERTY NAME="child3">MNO001366</PROPERTY>
            <PROPERTY NAME="child4">1507</PROPERTY>
            <PROPERTY NAME="child5" />
            <PROPERTY NAME="child6" />
            <PROPERTY NAME="ID detalu">PL.10.000033</PROPERTY>
        </ITEM>
        <ITEM>
            <PROPERTY NAME="[1]" />
            <PROPERTY NAME="child2">07</PROPERTY>
            <PROPERTY NAME="child3">MNO001485</PROPERTY>
            <PROPERTY NAME="child4">1626</PROPERTY>
            <PROPERTY NAME="child5" />
            <PROPERTY NAME="child6">Pintos</PROPERTY>
            <PROPERTY NAME="ID detalu">SHP001432</PROPERTY>
         </ITEM>
    </OBJECT>
</DATA>

我无法重现错误消息。不管怎样,要删除一个元素,你需要有一个对其父元素的引用,这样你就可以做到parent.remove(child)ITEM 元素的父元素是 OBJECT.

这是一个演示:

import xml.etree.ElementTree as ET
 
tree = ET.parse("PW.xml")
root = tree.getroot()
 
to_delete = []
 
object = root.find("OBJECT")
 
items = root.findall(".//ITEM")
 
# Find the items to delete and add them to the to_delete list
for item in items:
    prop = item.find("PROPERTY[@NAME='ID detalu']")
    if prop is not None and prop.text.startswith("SHP"):
        to_delete.append(item)
 
# Do the actual deletion of items
for item in to_delete:
    object.remove(item)
 
print(ET.tostring(root).decode())

输出:

<DATA>
    <OBJECT TYPE="Dane">
        <ITEM>
            <PROPERTY NAME="[1]" />
            <PROPERTY NAME="child2">07</PROPERTY>
            <PROPERTY NAME="child3">MNO001366</PROPERTY>
            <PROPERTY NAME="child4">1507</PROPERTY>
            <PROPERTY NAME="child5" />
            <PROPERTY NAME="child6" />
            <PROPERTY NAME="ID detalu">PL.10.000033</PROPERTY>
        </ITEM>
        </OBJECT>
</DATA>