python - 使用 python 和 lxml 删除元素

标签 python 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>

最佳答案

实现您想要的目标的一个更简单的选择是找到 <xxx:component> <entry> 内的元素组件并将其写入文件。

示例 -

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

关于python - 使用 python 和 lxml 删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32147315/

相关文章:

python - 使用 Python Lxml 解析静态 html 文件中的隐藏元素

Python XML 到记录

python - 多臂老虎机练习的反直觉结果

python - R - 如何将 HTML 代码嵌入到 Jupyter 笔记本输出中?

python - 停用 readline 自动完成

python - 使用带有 lxml 前缀的 fromstring()

Python 3.6 : rename column header using DictWriter

python - 如何创建随机对象列表?

python - 将 scrapy 转换为 lxml

html - 获取网站名称包含python 27中的HTML代码