473,395 Members | 1,738 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Subclassing cElementTree.XMLTreeBuilder

I found an earlier post about subclassing cElementTree.Element which
can't
be done because it is a factory method. I am trying to subclass
XMLTreeBuilder
with success using the python implementation, but not with
cElementTree.

[1013]$ python
Python 2.3.4 (#1, Feb 22 2005, 04:09:37)
[GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>import elementtree.ElementTree
class X(elementtree.ElementTree.XMLTreeBuilder):
.... pass
....
>>import cElementTree
class Y(cElementTree.XMLTreeBuilder):
.... pass
....
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot create 'builtin_function_or_method' instances
>>>
Is it possible to subclass cElementTree.XMLTreeBuilder?

Thanks,
Mike

Jan 25 '07 #1
2 2182
"mukappa" wrote:
Is it possible to subclass cElementTree.XMLTreeBuilder?
no, it's a factory function. if you need to extend it, you'll have to wrap it. but
I'm not sure I see the use case; what is it you're trying to do here?

</F>

Jan 25 '07 #2
On Jan 25, 4:32 am, "Fredrik Lundh" <fred...@pythonware.comwrote:
"mukappa" wrote:
Is it possible to subclass cElementTree.XMLTreeBuilder?no, it's a factory function. if you need to extend it, you'll have to wrap it. but
I'm not sure I see the use case; what is it you're trying to do here?

</F>
I'm trying to parse xmpp stanzas coming in over a socket. Since
cElementTree is
more efficient, I would like to use it when available.

Here is what I have now:

import logging
from elementtree import ElementTree

class StanzaTreeBuilder(ElementTree.XMLTreeBuilder):
"""Capture stanza elements (<streamchildren) from parser events.

Private methods are lifted from the old
elementtree.XMLTreeBuilder.FancyTreeBuilder
"""

def __init__(self, html=0):
"""Initialize state variables."""
ElementTree.XMLTreeBuilder.__init__(self, html)
self._parser.StartNamespaceDeclHandler = self._start_ns
self._parser.EndNamespaceDeclHandler = self._end_ns
self.namespaces = []
self.level = 0
self.stanza = None
self.streamelem = None

def _start(self, tag, attrib_in):
elem = ElementTree.XMLTreeBuilder._start(self, tag, attrib_in)
self.start(elem)

def _start_list(self, tag, attrib_in):
elem = ElementTree.XMLTreeBuilder._start_list(self, tag,
attrib_in)
self.start(elem)

def _end(self, tag):
elem = ElementTree.XMLTreeBuilder._end(self, tag)
self.end(elem)

def _start_ns(self, prefix, value):
self.namespaces.insert(0, (prefix, value))

def _end_ns(self, prefix):
assert self.namespaces.pop(0)[0] == prefix, "implementation
confused"

def start(self, element):
"""Track nesting level (capture open <streamon first
call)."""
logging.debug("start(%s): %s" %
(self.level, ElementTree.tostring(element)))
if self.streamelem is None:
assert element.tag == "http://etherx.jabber.org/streams"
self.streamelem = element
self.stanza = element
self.level += 1

def end(self, element):
"""Capture stanza when nesting level is 1."""
self.level -= 1
if self.level == 1:
self.stanza = element
self.streamelem.clear()
logging.debug("end(%s): %s" %
(self.level, ElementTree.tostring(element)))

def stanzagen(socket):
"""Yield open <stream ...on first call, then complete stanzas.

Caller needs 'id' from the opening <stream>, then he needs stanzas,
one per call. Works by parsing the socket one byte at a time, and
yielding complete stanza at earliest opportunity (or None if none
waiting), exits on EOF. Stanzas are returned as ElementTree
Elements
to give them a natural pythonic feel.

see
http://online.effbot.org/2004_12_01_archive.htm#element-generator"""
p = StanzaTreeBuilder()
data = None
while 1:
try:
data = socket.recv(1)
if not data:
logging.info("EOF from peer")
p.close()
break
p.feed(data)
if p.stanza is not None:
yield p.stanza
p.stanza = None
data = None
except:
if data is not None:
logging.error("error reading: %s" % (data))
raise
else:
yield None

Jan 25 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: BJörn Lindqvist | last post by:
A problem I have occured recently is that I want to subclass builtin types. Especially subclassing list is very troublesome to me. But I can't find the right syntax to use. Take for example this...
1
by: Kent Johnson | last post by:
Is it possible to subclass cElementTree.Element? I tried >>> import cElementTree as et >>> class Elt(et.Element): ... pass ... Traceback (most recent call last): File "<stdin>", line 1, in ?...
11
by: Brent | last post by:
I'd like to subclass the built-in str type. For example: -- class MyString(str): def __init__(self, txt, data): super(MyString,self).__init__(txt) self.data = data
27
by: Igor V. Rafienko | last post by:
Hi, I am trying to understand how cElementTree's clear works: I have a (relatively) large XML file, that I do not wish to load into memory. So, naturally, I tried something like this: from...
3
by: Diez B. Roggisch | last post by:
Hi, I've got to deal with a pretty huge XML-document, and to do so I use the cElementTree.iterparse functionality. Working great. Only trouble: The guys creating that chunk of XML - well, lets...
0
by: Mark | last post by:
I have an elementtree created with cElementTree. I then use ElementInclude to resolve some xinclude elements. But then I want to move those included elements to be children of the root ...
0
by: Mark | last post by:
-------- Original Message -------- Subject: Using cElementTree and elementtree.ElementInclude Date: Mon, 23 Oct 2006 09:40:24 -0500 From: Mark E. Smith <mark.e.smith@arnold.af.mil> Organization:...
1
by: Piet van Oostrum | last post by:
I have just installed Python 2.5 on Mac OS X 10.4.8 on an iBook (PPC) from the dmg. Now I tried to install cElementTree -1.0.5-20 from source (no egg available in cheeseshop) and got the following...
1
by: Barry | last post by:
I recently tried switching from ElementTree to cElementTree. My application parses a collection of large XML files and creates indexes based on certain attributes. This entire collection is saved...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.