Rob
Rob

Reputation: 90

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

I am new to python and xml parsing, so this may be a very dumb question. What is the best way to test if a given element if it is the root if the root is not known? So for example, given a generic test.xml structure;

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

And you have a function that takes in elements only. The only way I have come up so far is something like this, but requires the root to be known to the function

 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

Originally I tried

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

Since lxml treats elements similar to lists, I had expected it to return values for any children and None for the root that would not have a parent. Instead for the root it returns an error.

Upvotes: 2

Views: 1515

Answers (1)

gvanderest
gvanderest

Reputation: 116

I have never used lxml before, but by looking up the documentation and thinking about it a bit: The root would be the only element that does not have a parent, correct?

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])

Upvotes: 6

Related Questions