【问题标题】:remove attribute value using xpath and lxml python使用 xpath 和 lxml python 删除属性值
【发布时间】:2014-05-27 09:02:10
【问题描述】:

我正在使用以下代码访问 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])?我想以不同的方式对待他们。

【问题讨论】:

  • 显示您的 xml。另外,如果您选择/@attribute,您将获得一个属性列表,因此不需要额外查看它是标签还是属性。
  • 感谢您的回答..我的 xml 文件并不特别我想要做的是,如果给定的 xpath 指示一个属性,我的函数应该用 '' 替换它的值:例如,如果我的 xml 文件就像: 和 xpath 是:/root/@hello 我想找到一种方法将其转换为
  • 我的回答有帮助吗?如果是,请接受。如果不是,那是什么问题。

标签: python xml xpath lxml


【解决方案1】:

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

<root attribute="something"/>

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

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

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

【讨论】:

    猜你喜欢
    • 2017-07-13
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多