[Tutor] pyXML DOM 2.0 Traversal and filters
Levy Lazarre
llazarre@yahoo.com
Tue Apr 29 12:40:03 2003
Hi Fellow Listers,
Given the following sample file ('appliances.xml'), I
am trying to write a TreeWalker that would print out
the element
nodes, while a filter would prevent the nodes with a
status of "broken" from displaying.
<?xml version="1.0"?>
<appliances>
<clock status = "working">cuckoo</clock>
<television status = "broken">black and
white</television>
</appliances>
I am getting some exceptions, making me think that I
am calling the filter the wrong way or I am missing
something.
Can somebody please point me to the right direction?
Here is the sample code:
########### SNIP ####################
from xml.dom.ext.reader import Sax2
from xml.dom.NodeFilter import NodeFilter
# Rejects element nodes with a "status" attribute of
"broken":
def filterbroken(thisNode):
if (thisNode.nodeType == thisNode.ELEMENT_NODE and
thisNode.getAttribute("status") == "broken"):
return NodeFilter.FILTER_REJECT
return NodeFilter.FILTER_ACCEPT # else, accept
the node
# create Reader object
reader = Sax2.Reader()
input_file = file("appliances.xml")
doc = reader.fromStream(input_file) # Parse
the input file, get a DOM tree.
walker = doc.createTreeWalker(doc.documentElement,
NodeFilter.SHOW_ALL, filterbroken, 0)
while 1:
print walker.currentNode.nodeName, ': ',
walker.currentNode.nodeValue
next = walker.nextNode()
if next is None: break
input_file.close()
reader.releaseNode(doc)
##########################################
Here are the exceptions I am getting:
>>> appliances : None
Traceback (most recent call last):
File
"C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py",
line 301, in RunScript
exec codeObject in __main__.__dict__
File "C:\temp\Listing4.14.py", line 21, in ?
next = walker.nextNode()
File
"C:\Python22\Lib\site-packages\_xmlplus\dom\TreeWalker.py",
line 128, in nextNode
next_node = self.__advance()
File
"C:\Python22\Lib\site-packages\_xmlplus\dom\TreeWalker.py",
line 141, in __advance
if self.firstChild():
File
"C:\Python22\Lib\site-packages\_xmlplus\dom\TreeWalker.py",
line 85, in firstChild
if
self.__checkFilter(self.__dict__['__currentNode']) !=
NodeFilter.FILTER_REJECT:
File
"C:\Python22\Lib\site-packages\_xmlplus\dom\TreeWalker.py",
line 168, in __checkFilter
return self.__dict__['__filter'].acceptNode(node)
AttributeError: 'function' object has no attribute
'acceptNode'
There are no exceptions when the filter is replaced by
None in the 'walker =' statement.
Thanks in advance,
Levy Lazarre
Information Systems
Winter Haven Hospital
llazarre@yahoo.com
__________________________________
Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo.
http://search.yahoo.com