1

我正在尝试根据子内容查找特定标签并删除父标签和内容,但找不到答案。这是我的xml:

<video>
    <crew>
      <member billing="top">
        <name>Some Guy</name>
        <roles>
          <role>Painter</role>
          <role>Decorator</role>
        </roles>
      </crew>
      <crew billing="top">
        <name>Another Guy</name>
        <roles>
          <role>Primary</role>
        </roles>
      </crew>
    </crew>
</video>

我想要做的是搜索以查看块中是否<role>Primary</role>存在<crew>,如果存在,我想删除存在的整个<crew><role>Primary</role>,它是父块。所以结果是:

<video>
    <crew>
      <member billing="top">
        <name>Some Guy</name>
        <roles>
          <role>Painter</role>
          <role>Decorator</role>
        </roles>
      </crew>
</video>

它有时不是在最后,可能隐藏在许多其他<crew>标签中,所以我知道如果该块包含<role>Primary</role>我想删除<crew>它所在的整个块。我试过:

for find1 in root.iter(tag='role'):
    find1 = find1.text
    if find1 == "Primary":
        path = tree.xpath('//video/crew')
        etree.strip_elements(path, 'member')

但这会删除每个<crew>标签及其内容。亲切的问候。

4

1 回答 1

2

使用 xpath:

for crew in root.xpath('.//crew[descendant::role[contains(text(), "Primary")]]'):
    crew.getparent().remove(crew)
于 2013-07-11T13:28:53.253 回答