使用xpath和lxml python删除属性值

使用xpath和lxml python删除属性值,python,xml,xpath,lxml,Python,Xml,Xpath,Lxml,我使用以下代码访问xml文件中的属性值并将其删除 import lxml.etree as et def ignore_xpath(xmlFile,xpath): tree = et.parse(xmlFile) for elt in tree.xpath(xpath): elt='' print et.tostring(tree, pretty_print=True, xml_declaration=True) 但这对xpath不起作用:/root/

我使用以下代码访问xml文件中的属性值并将其删除

import lxml.etree as et
def ignore_xpath(xmlFile,xpath):
    tree = et.parse(xmlFile)
    for elt in tree.xpath(xpath):
        elt='' 
    print et.tostring(tree, pretty_print=True, xml_declaration=True)
但这对xpath不起作用:
/root/@attribute


我做错了什么?我如何知道我的
elt
是属性还是标记(case xpath=
/root[@attribute]
)?我想以不同的方式对待它们。

您不能删除所选的属性。必须选择包含该属性的元素(标记)。我假设您的文档如下所示:

<root attribute="something"/>
for elt in tree.xpath("/root"):
    elt.set("attribute", "")
print et.tostring(tree, pretty_print=True, xml_declaration=True)

执行
elt=''
时,只需替换引用,而不是实际属性。

显示xml。此外,如果选择
/@attribute
,您将获得一个属性列表,因此,不需要额外查看它是标记还是属性。谢谢你的回答..我的xml文件并不特殊。我想做的是,如果给定的xpath指示一个属性,我的函数应该将其值替换为“”:例如,如果我的xml文件类似于:并且xpath是:/root/@hello,我想找到一种方法将其转换为我的xml文件回答帮助?如果是,请接受。如果没有,问题是什么。