【发布时间】:2016-03-01 23:09:30
【问题描述】:
我正在尝试从字符串构建 ElementTree。当我执行以下操作时(如Python ElementTree: Parsing a string and getting ElementTree instance 中所述),我得到一个 Element 而不是 ElementTree:
companyTree = ElementTree.ElementTree(ElementTree.fromstring('<companies></companies>'))
如果我这样做
print(companyTree.getroot())
我明白了
AttributeError: 'xml.etree.ElementTree.Element' 对象没有属性 'getroot'
换句话说,companyTree 是 Element 而不是 ElementTree。根据1 中接受的答案,我应该得到一个 ElementTree。 API 有变化吗?我现在如何从字符串中获取 ElementTree?谢谢。
请注意,Python ElementTree: ElementTree vs root Element 中有更多关于此问题的内容
【问题讨论】:
-
root和companyTree有什么关系? -
是的,这有点不清楚。 companyTree = root(传递给具有 root 的方法)。已编辑。
-
我无法重现该错误。执行
print(companyTree.getroot())打印出<Element 'companies' at 0x009B1630>。 -
你是绝对正确的。传递给 ElementTree 的函数中存在错误并导致上述异常。谢谢。
标签: python xml python-3.x elementtree