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