etree xml 解析和删除

etree xml parsing and deletion

如何删除或移除 server1 的所有条目,包括标签?我尝试使用 etree 删除功能,但它没有帮助

  <hosts>
    <host instances="" name="*" roles="alpha">
      <tags/>
    </host>
    <host instances="" name="server1" id="alpha,beta">
      <tags>
        <tag app-id="1" instance="1" name="alpha"/>
        <tag app-id="2" instance="2" name="beta"/>
      </tags>
    </host>
    <host instances="" name="server2" id="beta,gama">
      <tags>
        <tag app-id="1" instance="1" name="beta"/>
        <tag app-id="2" instance="2" name="gama"/>
      </tags>
    </host>
</hosts>


def main1(file=outfile):
 tree = et.parse(file)
 root = tree.getroot()
 thingy = root.find('hosts')
 for thing in thingy:
    if "server1" in thing.get('name'):
        root.remove(thing)
        #thingy.remove(thing)
    print thingy

需要父对象从 HTML/XML 中删除其子对象。

使用 getparent() 方法获取父级,然后使用 remove() 方法删除其 chid 标签。

演示:

>>> import lxml.etree as PARSER
>>> root = PARSER.fromstring(data)
>>> root.xpath("//hosts/host[@name='server1']")
[<Element host at 0xb6d2ce6c>]
>>> a = root.xpath("//hosts/host[@name='server1']")
>>> for i in a:
...    pp = i.getparent()
...    pp.remove(i)
... 
>>> PARSER.tostring(root, method="xml")

A. find return None 以下代码的对象。

>>> thingy = root.find('hosts')
>>> thingy

这应该是thingy = root.find('host')

B.使用xpath方法获取目标标签。