pyxie (version 1.08)
index
/home/graeme/CVS/dna/xsd/python/pyxie.py

Pyxie
An Open Source XML processing library for Python
 
                         The Pyxie Project
                        http://www.pyxie.org
 
Disclaimer
 
THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL PROPYLON OR ITS CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
        
http://www.pyxie.org
 
XML Processing with Python
Prentice Hall
 
Sean Mc Grath
 
Change Log:
Version 1.08 - 27 Aug 2001  (Derek Higgins)
  Changed the functions WalkElements and WalkData to call the appropriate function 
  upon the end of each element once and only once. 
  (Thanks to Rob van Wees for the bug report)
 
Version 1.07 - 2 Aug 2001  (Derek Higgins)
  Change to escape backslashes in the content properly 
  (Thanks to John Cowan for pointing out the problem)
 
Version 1.06 - 8 Feb 2001
 Support for Python 2.0 added. In Python 2.0, the pyexpat module has been renamed
 to expat. Pyxie now tries to import pyxepat, and if that failed, imports
 expat. Should now would with Python 1.5.x and 2.0
 (Thanks Tim (and some others whose name I forget, sorry.))
 
Version 1.05 - 24 October 2000
 Changed StartElementHandler to cope with the more recent versions
 of pyexpat that use a dictionary rather than a list to represent
 attributes (thanks John)
 
Version 1.01 - 16 March 2000
 xDispatch.Dispatch bug fixed (processing instructions) (Thanks Chris)
 xTree.PasteDown bug fixed (Thanks Noel)
 
Version 1.02 -  7 April 2000
Added Envelope function based on a feature request from Stuart
Hungerford. (Thanks Stuart).
 
Version 1.03 - 1 August 2000
Fixed bug with PIs (Thanks John)
 
Version 1.04 - 3 August 2000
Fixed bug in and improved structure of NWS (Thanks John)
 
Introduction
------------
The Pyxie library provides facilities for processing XML. The library
uses a simple notation to capture the information generated by XML
parsers known as PYX.
 
PYX is a line oriented notation in which the first character serves
to specify what type of parsing event the line represents:
 
--------------------------
First         Parsing
Character     Event
--------------------------
(              Start-tag
A              Attribute
)              End-tag
-              Data
?              Processing
               Instruction
--------------------------
 
Line ends and tabs occuring in data or attribute lines are escaped
to "" followed by "n" and "" followed by "t" respectively. 
 
Any process that generates information in PYX can be
used as a data source for this library - relational databases,
HTML parsers, SGML parsers, XML parsers, latex parsers... whatever.
 
Facilities provided include:
        Tree-driven XML Processing (see xTree and related classes)
        Event-driven XML Processing (see the xDispatch class)
        Event-driven XML Processing with full Tree access
        (see the Dispatch method of xTree)
        Sparse Trees - (see demo in test harness)
        A SAX to PYX driver to generate PYX from any SAX parser
        An SGML-like white space normalization function
        A Pyxie Exception class
        PYX encoder and decoder functions for handling escaped
        line ends/tabs
        
Tree driven XML Processing
---------------------------
The xTree class provides:
        Navigational methods for moving current position around
        a tree structure
        Cut and Paste facilities
        Serialization to XML via repr
        Node list assembly methods such as Ancestors, Descendants etc.
        Tree walking with call-backs to methods named after element
        type names
        A "Pythonic" tree walking facility using a simple Python for loop
        An event dispatch facility (Dispatch) which will can call handler
        methods in arbitrary Python classes
        
 
Event-driven XML Processing
---------------------------
The xDispatch class provides:
        Ancestor information available in a simple list structure
        Callbacks to methods named after element type names
        e.g. start_foo, end_foo
        Default method handlers default_start and default_end
        Callback for data content (the characters method)
        Supports sparse tree building by allowing dispatched events
        to be pushed back onto the PYX stream (see demo in test harness)
 
The xDispatchMultiplexor class provides the ability to have
multiple event-driven "clients" processing a PYX event stream
in parallel.
 
See also the Pyxie project home page at http://www.pyxie.org.
 
There is a Pyxie mailing list. For more information, send an e-mail
with just the word 'help' as subject or body to:
    pyxie-request@starship.python.net

 
Modules
       
cStringIO
cStringIO
string
types

 
Classes
       
exceptions.Exception
PyxieException
xDispatch
xDispatchMultiplexor
xNode
xData
xElement
xTree

 
class PyxieException(exceptions.Exception)
    # An exception base class for Pyxie
# ---------------------------------
 
  Methods defined here:
__init__(self, s='')
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class xData(xNode)
    xData: a node representation of XML data content
 
  Methods defined here:
__init__(self, str)
__repr__(self)
Return the XML representation of an xData node.
The XML represetation of an xData node is simply the
data content of the node
__setslice__(self, i, j, s)
Convenience slicing method to allow assignment to a slice
of the data content of an xData node
__str__(self)
Return a meaningful string representation of an xData object.
Returns the first 10 characters

 
class xDispatch
    xDispatch: a Class supporting event-driven XML processing
via callback methods
 
start_foo    : start of element foo
end_foo      : end of element foo
characters   : character data
default_start: start of element with no specified handler
default_end  : end of element with no specified handler
processinginstruction: processing instruction
 
Keeps track of ancestors and their descendants in the
Ancestors instance method.
 
Allows PYX events to be pushed back onto the
stream of events (used to support sparse tree building)
 
Can act as a data source for PYX2xTree.
 
  Methods defined here:
Dispatch(self, fo=None)
Process a PYX source calling any callback methods
defined in this class
PushElement(self, etn, attrs)
Given an element type name and an attribute dictionary
xElement, push the PYX events necessary to create
it onto a stack of events. This is used to support
sparse tree building
Sanitize(self, s)
Replace periods with underscores so that an element called
x.y will have  handler methods called start_x_y and end_x_y
__init__(self, fo=None)
readline(self)
Return the next line of PYX. Any PYX pushed via
previous PushElement() calls take precedence.

 
class xDispatchMultiplexor(xDispatch)
    xDispatchMultiplexor: A class for parallel dispatch of XML events
# -----------------------------------------------------------------
 
  Methods defined here:
RegisterSink(self, object)
Register a sink with the Multiplexor
__init__(self, fo=None)
characters(self, data)
For each registered sink, see if it has a character
handler.
default_end(self, etn)
For each registered sink, see if it has an end handler
specifically for this element type. Failing that, see
if it has a default end handler
default_start(self, etn, attrs)
For each registered sink, see if it has a start handler
specifically for this element type. Failing that, see
if it has a default start handler
processinginstruction(self, target, data)
For each registered sink, see if it has a processing
instruction handler.

Methods inherited from xDispatch:
Dispatch(self, fo=None)
Process a PYX source calling any callback methods
defined in this class
PushElement(self, etn, attrs)
Given an element type name and an attribute dictionary
xElement, push the PYX events necessary to create
it onto a stack of events. This is used to support
sparse tree building
Sanitize(self, s)
Replace periods with underscores so that an element called
x.y will have  handler methods called start_x_y and end_x_y
readline(self)
Return the next line of PYX. Any PYX pushed via
previous PushElement() calls take precedence.

 
class xElement(xNode)
    xElement: A node representation of an XML element
consisting of elment type name and attribute
information
 
  Methods defined here:
__init__(self, ElementTypeName)
__repr__(self)
Return an XML serialization of an xElement
__str__(self)
Return a meaningful representation of an xElement

 
class xNode
    xNode: All nodes in a Pyxie tree are derived from the xNode
abstract base class.
All nodes can be connected to other nodes, up, down, left
and right.
 
  Methods defined here:
__init__(self)

 
class xTree
    xTree : a Python representation on an XML document
as a hierarchical data structure made up of
interconnected nodes
 
  Methods defined here:
Ancestors(self, n=None)
Create a list of the Ancestors of the current node
or the specified node.
Ancestors1(self, res, n)
Create a list of the ancestors of node "n" adding the child
nodes to the result list "res"
AtData(self)
Predicate method. Is current position data?
AtElement(self, etn=None)
Predicate method. Is current position an Element?
The optional argument allows the method to check
for a particular element type name
Children(self, n=None)
Create a list of the children of the current node
or the specified node. Most of the work is done by
the recursive Children1 method.
Children1(self, res, n)
Create a list of the children of node "n" adding the child
nodes to the result list "res"
Cut(self)
Cut out tree rooted at current position and return it
as a new tree
New Current Position is set to parent of current node
Descendants(self, n=None)
Create a list of the descendants of the current node
or the specified node. Most of the work is done by
the recursive Descendants1 method
Descendants1(self, res, n)
Add descendants of node "n" to theresult list "res".
This is an internal recursive method invoked from
the Descendants method
Dispatch(self, obj)
Down(self)
Set current position to first child of current node
GetUp(self)
Return parent of current node
HasDown(self)
return true if current position has a child
HasLeft(self)
return true if current position has left sibling
HasRight(self)
return true if current position has a right sibling
HasUp(self)
return true if current position has a parent
Home(self)
Set current position to root node
JoinData(self, sep, n=None)
Create a string by concatenating the data content of
an element node. A seperator string will be spliced
between adjacent data items
Left(self)
Set current position to previous  sibling of current node
PYX2xTree(self, f)
Build an xTree from a PYX source.
PasteDown(self, l)
Paste the specified tree into this tree as first child
of current position
PasteRight(self, l)
Paste the specified tree into this tree as next sibling
of current position
PopPos(self)
Pop a position from the position stack and make it
the current position
PushPos(self)
Push the current position onto a position stack for later
retrieval via the PopPos method.
Right(self)
Set current position to first sibling of current node
Seek(self, Node)
Set current position to the specified node
Up(self)
Set current position to parent of current node
Walk(self, func)
Walk the descendants of the current position, calling
the specified function twice for each node. Once
"on the way down" and once "on the way up"
WalkData(self, func)
Walk the data descendants of the current position, calling
the specified function twice for each data node. Once
"on the way down" and once "on the way up"
WalkElements(self, func)
Walk the element descendants of the current position, calling
the specified function twice for each element node. Once
"on the way down" and once "on the way up"
ZapTree(self)
Delete an xTree object completely by deleting the xNode objects
attached to it. The xNodes are joined in a circular fashion and
so the links need to be broken to allow Python's reference
counting garbage collector to process them
__del__(self)
When an xTree is garbage collected we need
to break the circular
references joining the xNode objects together.
__getattr__(self, n)
Allow attributes of the current xElement or xData node to
be accessed as attributes of the xTree object. Particularly
useful for ElementTypeName and Data attributes. i.e.
Instead of saying:
  "tree.CurPos.Data" can simply say "tree.Data"
Instead of saying:
  "tree.CurPos.ElementTypeName" can simply say
  "tree.ElementTypeName"
__getitem__(self, n)
Allow a tree to be iterated using Python's for loop
__init__(self, rootnode=None)
Construct an xTree. A root node (xElement) can be provided
if desired. (This is especially useful when doing sparse tree
building.
__repr__(self)
Return xml serialization of an xTree

 
Functions
       
DataNodes(nodelist)
Filter a node list to the character data nodes
ElementTypeNames(nodelist)
Filter a node list to the names of its xElement nodes
Elements(nodelist, elist=[])
Filter a node list to xElement nodes
Envelope(t, SourceElementType, EnvelopeElementType)
File2PYX(filename)
Return a PYX source built from the XML in the specified file.
Uses PyExpat as the XML parser
File2xTree(filename)
Return an xTree built from the XML in the specified file.
Uses PyExpat as the XML parser
NormalizeWhiteSpaceSMG(t)
Normalize white space SMG (Sean McGrath style)
 
A SGML-ish white space processing algorithm for xTree objects.
 
- A line end immediately after a start-tag is ignored
- A line end immediately before an end-tag is ignored
- all other line ends are treated as spaces
- No white space processing performed anywhere in an element
- where xml:space=="preserve" anywhere in the ancestry of
- the element
PYExpat2PYX(fo)
Utility function to create PYX notation from a SAX
parser
PYX2xTree(f)
Build an xTree from a file-like object.
Input in PYX format
returns xTree
Optionally, root the new tree at a specified root node
PYXDecoder(s)
Replace any escaped tab or newline characters with literlal tabs
and newlines
PYXEncoder(s)
Replace any tab or newline characters with escaped forms
SAX2PYX(fo, ParserSelection=None)
String2PYX(str)
Return a PYX source from an XML instance provided in a string
Uses PyExpat as the XML parser
String2xTree(str)
Create an xTree from an XML instance provided in a string
Uses PyExpat as the XML parser

 
Data
        __version__ = '1.08'