We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Python
- XML
- XML 1 - Find the Score
- Discussions
XML 1 - Find the Score
XML 1 - Find the Score
Sort by
recency
|
193 Discussions
|
Please Login in order to post a comment
def get_attr_number(node): n = 0 if len(node.attrib) !=0: n+= len(node.attrib) for child in node: n +=get_attr_number(child) return n
def get_attr_number(node): import xml.etree.ElementTree as etree tree = etree.ElementTree(etree.fromstring(xml))
This one-liner, below uses node.iter() and therefore does not need to use recursion:
Another way, below, uses a for loop (effectively the built-in function iter(node) and needs recursion:
To understand the above, read the ElementTree doc: https://diveintopython3.net/xml.html
It says " You can use the element itself as an iterator to loop through all of its child elements."
You will see some people using len(node) along with recursion. Others use node.iter() to retrieve all elements in the tree (node, children and subchildren) in one go.