2013-07-11 178 views
1

我想找到一个特定的标签,基于它的孩子的内容和删除父标签和内容,但无法找到答案。这里是我的xml:基于子标签值删除标签和内容 - python lxml

<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> 

我想要做的就是搜索,看是否存在于<crew><role>Primary</role>,如果它想删除整个<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>标签和它的内容。 亲切的问候。

+0

给定的XML是无效的。 – falsetru

回答

2

使用XPath:

for crew in root.xpath('.//crew[descendant::role[contains(text(), "Primary")]]'): 
    crew.getparent().remove(crew) 
+0

非常好的解决方案,非常感谢。 – speedyrazor

+0

这是有效的,但删除两个工作人员,我只想删除其中的主要人。 – speedyrazor

+0

@ user2446702,使用问题中给出的xml,我的答案代码只删除'Another Guy'。 – falsetru