lxml中测试元素是否为根的最佳方法

Best way in lxml to test if an element is the root

我是 python 和 xml 解析的新手,所以这可能是一个非常愚蠢的问题。如果根未知,则测试给定元素是否为根的最佳方法是什么?因此,例如,给定一个通用的 test.xml 结构;

<root>
<child1>
<child2>
<child3>Some Text</child3>

而且你有一个只接收元素的函数。到目前为止我提出的唯一方法是这样的,但需要函数知道根

 from lxml import etree as ET
 fulltree = ET.parse('test.xml')
 root = fulltree.getroot()

def do_stuff_with element (element):
       if (element is not root[0].getparent()): #Only works if root is known
       #do stuff as long as element is not the root
       else:
       #if we are at the root, then do nothing
       return

本来我试过

      if (len(element.getparent()):  #return None if the parent

因为 lxml 对待元素类似于列表,我曾期望它对任何子元素具有 return 值,对没有父元素的根元素具有 None 值。而对于根来说,它 return 是一个错误。

我以前从未使用过 lxml,但通过查找文档并稍微考虑一下:根将是唯一没有父元素的元素,对吗?

from lxml import etree as ET
fulltree = ET.parse('test.xml')


def do_stuff_with_element(element):
    if element.getparent() is None:
        print("Element is root")
    else:
        print("Element is not root")


root = fulltree.getroot()
do_stuff_with_element(root)
do_stuff_with_element(root.getchildren()[0])