gpt4 book ai didi

python - 使用 python 和 lxml 删除元素

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:06 25 4
gpt4 key购买 nike

我需要从此 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com