我可能会忽视某些事情,但我得到了一个课程"解析"功能" getAllElements"。在主脚本中,我使用
导入解析from parseXML import parse.
然后我做
parse = parse(file)
工作正常。但是当我做的时候
print parseXML.parse(file).getAllElements()
我收到以下错误:
NameError: global name 'getAllElements' is not defined
以下是代码。我哪里错了?
编辑:在评论后更改了代码
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()
答案 0 :(得分:1)
看起来parseXML
不在您的本地命名空间中,因为您正在执行from parseXML import parse
。您是否尝试直接导入parseXML
并执行此操作?
import parseXML
parseXML.parse(file).getAllElements()
您正在获取NameError,因为您无法在方法中调用getAllElements()
。它必须是self.getAllElements()
。
正如评论中所提到的,代码中还有其他逻辑错误需要纠正。
答案 1 :(得分:1)
正如Praveen所暗示的那样,这是你的进口和风格。
因为你以这种方式导入:
from foo import bar
您不需要(实际上不应该)在您的通话中明确声明foo。
bar.baz()
不
foo.bar.baz()
所以在你的情况下试试电话:
parse(file).getAllElements()
但是你还需要在你的递归中解决裸调用: getAllElements()可能应该是self.getAllElements()