0

I wrote a method that seems to work correctly to recursively go throug a xml. But it returns a None instead of a string. I figured out that it has something to do with the way I call the recursive function but can't figure out how to make it work. The print("returning: {}".format(path) prints the correct result but the returned value is None.

Here is my code:

  # retrieves the path of an given xml-node
def getParentValueAndId(self,node, path):
    actual_node = node.getparent().getparent().getparent().find(self.openEHR_prefix + "rm_attribute_name")
    node_id = node.getparent().getparent().find(self.openEHR_prefix + "node_id").text
    if (path == "value" and node_id is not None):
        path = "/{}[{}]/{}".format(actual_node.text, node_id, path)
        try:
            self.getParentValueAndId(actual_node, path)
        except:
            pass
    elif not (node_id is None):
        path = "/{}[{}]{}".format(actual_node.text, node_id, path)
        try:
            self.getParentValueAndId(actual_node, path)
        except:
            print("returning: {}".format(path))
            return path
    else:
        try:
            self.getParentValueAndId(actual_node, path)
        except:
            pass
  • Aren't you getting any exceptions from those paths that you don't return anything in them? In your code, if you don't return anything from just one `getParentValueAndId` call, the entire recursive call would return `None`. – Ali Tou Apr 27 '20 at 12:09
  • 1
    I didn't quite look through your code, but shouldn't there be returns before the `self.getParentValueAndId()` calls? – Maxxik CZ Apr 27 '20 at 12:09
  • You are returning results in one case only. In recursive methods, we need to return some result for every recursive iteration. You are getting None because the function is exiting from some other case where you haven't returned anything. – Hashir Baig Apr 27 '20 at 12:10
  • I already had a return before the self.getParentValueAndId() and it doesn't change anything – Andy Who_is Apr 27 '20 at 12:26
  • I re-wrote the returns before the self.getParentValueAndId() calls and it worked. Thanks – Andy Who_is Apr 27 '20 at 12:47
  • it almost worked, my first String is still None – Andy Who_is Apr 27 '20 at 13:16

0 Answers0