I read the following: "Deprecated since version 3.2, will be removed in version 3.9: Use list(elem) or iteration." ( https://docs.python.org/3.8/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getchildren )
My code works for python 3.8 and below:
tree = ET.parse("....xml")
root = tree.getroot()
getID= (root.getchildren()[0].attrib['ID'])
However, when I try to update it for python 3.9, I am unable to
tree = ET.parse("....xml")
root = tree.getroot()
getID= (root.list(elem)[0].attrib['ID'])
I get the following errors AttributeError: 'xml.etree.ElementTree.Element' object has no attribute 'list'
"Use list(elem)
or iteration" means literally list(root)
, not root.list()
. The following will work:
getID = list(root)[0].attrib['ID']
You can wrap any iterable in a list, and the deprecation note specifically tells you root
is iterable. Since it's rather inefficient to allocate a list for just one element, you can get the iterator and pull the first element from that:
getID = next(iter(root)).attrib['ID']
This is a more compact notation for
for child in root:
getID = child.attrib['ID']
break
The major difference is where the error will get raised when there is no child (directly by next
vs when you try to access the non-existent getID
variable).
the error is indicating you should write this:
getID = list(root)[0].attrib['ID']
invoking list
iterates over the root
element giving its children and at the same time converting it to a list which can be indexed
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.