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>
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Originally I tried
if (len(element.getparent()): #return None if the parent
Run Code Online (Sandbox Code Playgroud)
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.
小智 5
我以前从未使用过 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])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
826 次 |
| 最近记录: |