使用XPath和lxml在Python中删除属性值
我正在使用以下代码来访问 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
你不能直接删除你选择的属性。你需要选择包含那个属性的元素(标签)。我假设你的文档是这样的:
<root attribute="something"/>
然后你可以这样做:
for elt in tree.xpath("/root"):
elt.set("attribute", "")
print et.tostring(tree, pretty_print=True, xml_declaration=True)
当你执行 elt = ''
时,你只是替换了引用,而不是实际删除了那个属性。