【问题标题】:lxml tree.find is not workinglxml tree.find 不工作
【发布时间】:2017-06-23 11:03:58
【问题描述】:

我遇到了命令 find 的问题,它无法正常工作。但是,理论上它应该可以工作。

假设我有这个 xml 文件:

<?xml version="1.0"> 
<pxml name="es">
   things here
</pxml

我想找到元素 pxml 来添加一个属性。所以我正在使用这段代码:

from lxml import etree as et
lang = 'de'
tree = et.parse("file.xml")
root = tree.getroot()
txml_element = root.find('//pxml')
txml_element.attrib['language'] = lang

我收到以下错误消息:

SyntaxError: cannout use absolute path on element

另外,如果我不做 tree.getroot 并且我在树中使用 find 我总是一个 None 元素。我错过了什么?

我不明白为什么会收到此消息错误。此外,如果仅使用 root.find('pxml') 它返回 None。

但是,使用 xpath 我得到了一个元素列表,它可以工作:

lang = 'de'
tree = et.parse("file.xml")
root = tree.getroot()
txml_elements = root.xpath('//pxml')
for element in txml_elements:
    element.attrib['language'] = lang
    print(element.attrib)
#print (et.tostring(tree))

【问题讨论】:

    标签: python python-3.x lxml


    【解决方案1】:

    尝试使用点:

    root.find('.')
    

    如果您只需要 pxml 元素,请检查标签

    txml_element.tag
    

    https://repl.it/IzNt/2

    【讨论】:

    • 谢谢 :) 它在这里工作。但是,如果我需要找到位于树中间的元素,我将继续遇到同样的问题,我无法使用 find,因为它返回 None 或问题正文中提到的错误。
    猜你喜欢
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    相关资源
    最近更新 更多