使用 python 和 lxml 删除元素

removing elements using python and lxml

我需要从此 xml -

中删除以下内容
<entry>
    <id>1234</id>
    <title>hello</title>
    <source>com.server.webclient.xxx</source>
    <xxx:component>
        <xxx:id>2134</xxx:id>
        <xxx:name>name</xxx.name>
    </xxx:component>
</entry>

我想要做的是删除 <entry><id><title><source>

我的代码试图立即删除 ID,但没有返回错误,也没有删除值。

with open('c:\temp\%s.xml' % args.componentName, 'w') as f:
    xmlObject = etree.fromstring(r.content)
    for elem in xmlObject.xpath( '//id' ) :
        elem.remove(elem)
    f.write(etree.tostring(xmlObject, pretty_print=True))

这就是我想要 XML 的样子 -

<xxx:component>
    <xxx:id>2134</xxx:id>
    <xxx:name>name</xxx.name>
</xxx:component>

一个更简单的选择是在 <entry> 组件中找到 <xxx:component> 元素并将其写入文件。

例子-

with open('c:\temp\%s.xml' % args.componentName, 'w') as f:
    xmlObject = etree.fromstring(r.content)
    reqElem = xmlObject.xpath('//xxx:component',namespaces=ns)   #ns should have the `xxx` prefix and whatever its actual namespace is
    if len(reqElem) == 1:
        f.write(etree.tostring(reqElem[0], pretty_print=True))