I’m probably overlooking something, but I got a class “parse” with a function “getAllElements”. In the main script I import parse using
from parseXML import parse.
Then I do
parse = parse(file)
which works fine. But when I do
print parseXML.parse(file).getAllElements()
I get the following error:
NameError: global name 'getAllElements' is not defined
Below is the code. Where am I going wrong?
Edit: changed the code after comment
class parse:
# Constructor
def __init__(self, file):
# parse the xml file into a tree
tree = xml.parse('/homes/ndeklein/test.featureXML')
# Get the root node of the xml file
self.rootElement = tree.getroot()
# Set self.parent to rootElement, because the first element won't have a parent (because it is the root)
self.parent = 'rootElement'
# dictionary that contains the parent -> child relation
self.parentChildDict = {}
# Go recursively through all the elements in the xml file, starting at the choosen rootElement, until only leaves (elements that don't contain elements) are left
# Return all the elements from the xml file
def getAllElements(self):
# if this is the first time this parent is seen:
# make elementDict with parent as key and child as value in a list
if not self.parentChildDict.has_key(self.parent):
self.parentChildDict[self.parent] = [self.rootElement]
# else: add the child to the parent dictionary
else:
self.parentChildDict[self.parent].append(self.rootElement)
for node in self.rootElement:
# if the len of rootElement > 0 (there are more elements in the element):
# set self.parent to be node and recursively call getAllElements
if len(self.rootElement) > 0:
self.parent = node
getAllElements()
return self.parentChildDict
.
#!/usr/bin/env python
# author: ndeklein
# date: 08/02/2012
# function: calls out the script
import parseXML
import xml.etree.cElementTree as xml
import sys
#Parse XML directly from the file path
file = '/homes/ndeklein/EP-B1.featureXML'
# parse the xml file into a tree
print parseXML.parse(file).getAllElements()
It’s your import and style of call, as Praveen alluded to.
Because you import in this fashion:
You don’t need to (and in fact shouldn’t) explicitly declare foo in your call.
Not
So in your case try the call:
But you still need to address the naked call in your recursion:
getAllElements() probably should be self.getAllElements()