使用xpath和lxml python删除属性值

时间:2014-05-27 09:02:10

标签: 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/@attribute

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

1 个答案:

答案 0 :(得分:0)

您无法删除所选的属性。您必须选择包含该属性的元素(标记)。我将假设您的文件如下:

<root attribute="something"/>

然后您可以执行以下操作:

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

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