Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7951311
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T02:31:21+00:00 2026-06-04T02:31:21+00:00

I’ve got a function to return a list from an etree element, but it

  • 0

I’ve got a function to return a list from an etree element, but it doesn’t look through nested elements.

<elem>
    <variable id="getthis">
        <!-- / -->
    </variable>
    <if>
        <variable id="alsoGetThis">
            <!-- Keep looping through all elements -->
        </variable>
    </if>
</elem>

(I’m working with Valid XML)

So currently the variable within the <if> is ignored, so how can you loop through all levels of the tree? I’m assuming this is a simple task, but maybe I’m wrong. (I’m new to Python & don’t always think like a programmer)

Python func to get the variables:

def collect_vars(self, elem):
    elemVars = []
    if elem.tag == 'variable':
        elemVars.append(elem.attrib['id'])
    elif e in elem == 'variable': # don't want to be doing these
        elemVars.append(e.attrib['id'])
    return elemVars

So all I want to end up with is the list elemVars containing all the variable IDs within the given <elem>

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T02:31:23+00:00Added an answer on June 4, 2026 at 2:31 am

    The problem you are facing is that you are not visiting all nodes in the file. You are only visiting the children of the elem element, but you are not visiting the children of these elements. To illustrate this, running the following (I have edited your XML to be valid):

    from xml.etree.ElementTree as etree
    
    xml_string = """<elem>
        <variable id="getthis" />
        <if>
            <variable id="alsoGetThis" />
        </if>
        </elem>"""
    
    e = etree.fromstring(xml_string)
    
    for node in e:
        print node
    

    results in

    <Element variable at 7f53fbdf1cb0>
    <Element if at 7f53fbdf1cf8>
    

    So you are not visiting the child variable of the node if. You will need to recursively visit each node in your XML file, i.e. you function collect_vars will need to call itself. I’ll post some code in a bit to illustrate this.

    Edit: As promised, some code to get all id attributes from your element tree. Rather than using an accumulator as Niek de Klein has I have used a generator. This has a number of advantages. For example, this returns the ids one at a time, so you can stop processing at any point, if, for example, a certain id is encountered, which saves reading the entire XML file.

    def get_attrs(element, tag, attr):
        """Return attribute `attr` of `tag` child elements of `element`."""
    
        # If an element has any cildren (nested elements) loop through them:
        if len(element):
             for node in element:
                # Recursively call this function, yielding each result:
                for attribute in get_attrs(node, tag, attr):
                    yield attribute
    
        # Otherwise, check if element is of type `tag` with attribute `attr`, if so
        # yield the value of that attribute.
        if element.tag == 'variable':
            if attr in element.attrib:
                yield element.attrib[attr]
    
    ids = [id for id in get_attrs(e, 'variable', 'id')]
    
    print ids
    

    This yields the result

     ['getthis', 'alsoGetThis']
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am currently running into a problem where an element is coming back from
I want to construct a data frame in an Rcpp function, but when I
I want to count how many characters a certain string has in PHP, but
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
Seemingly simple, but I cannot find anything relevant on the web. What is the
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.