首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >etree解析与删除

etree解析与删除
EN

Stack Overflow用户
提问于 2015-12-17 13:04:53
回答 1查看 40关注 0票数 2

如何删除或删除server1的所有条目,包括标记?我试过使用etree删除功能,但没有帮助。

代码语言:javascript
复制
  <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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-17 13:16:55

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

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

Demo

代码语言:javascript
复制
>>> 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返回用于以下代码的None对象。

代码语言:javascript
复制
>>> thingy = root.find('hosts')
>>> thingy

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

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34335325

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档