"This module provides access to the Xalan XSLT transformation engine."
# Copyright (C) Brian Quinlan. All rights reserved.
# For information about Pyana, visit:
# http://pyana.sourceforge.net/
from _Pyana import *
# Node types
ELEMENT_NODE = 1
ATTRIBUTE_NODE = 2
TEXT_NODE = 3
CDATA_SECTION_NODE = 4
ENTITY_REFERENCE_NODE = 5
ENTITY_NODE = 6
PROCESSING_INSTRUCTION_NODE = 7
COMMENT_NODE = 8
DOCUMENT_NODE = 9
DOCUMENT_TYPE_NODE = 10
DOCUMENT_FRAGMENT_NODE = 11
NOTATION_NODE = 12
# ExceptionCode - values used in DOMException
INDEX_SIZE_ERR = 1
DOMSTRING_SIZE_ERR = 2
HIERARCHY_REQUEST_ERR = 3
WRONG_DOCUMENT_ERR = 4
INVALID_CHARACTER_ERR = 5
NO_DATA_ALLOWED_ERR = 6
NO_MODIFICATION_ALLOWED_ERR = 7
NOT_FOUND_ERR = 8
NOT_SUPPORTED_ERR = 9
INUSE_ATTRIBUTE_ERR = 10
INVALID_STATE_ERR = 11
SYNTAX_ERR = 12
INVALID_MODIFICATION_ERR = 13
NAMESPACE_ERR = 14
INVALID_ACCESS_ERR = 15
def transform2String(source, style, params = {}):
"""transform2String(source, style, [, params ]) => string
Transform the XML document specified by "source", using the XSLT
stylesheet specified by "style", returning the result as a
string.
The "source" and "style "arguments can be files, strings or Pyana
URIs. The "style" argument may be None, in which case the source
XML file must contain a processing instruction.
If provided, "params" should be a dictionary containing
variable names as keys and XPaths as values.
The prefered means of calling this function is through keyword
arguments."""
t = Transformer()
t.setStylesheetParams(params)
return t.transform2String(source, style)
def transform2File(source, style, file, params = {}):
"""transform2File(source, style, file, [, params ])
Transform the XML document specified by "source", using the XSLT
stylesheet specified by "style", writing to the file whose name
is given in "file".
The "source" and "style" arguments can be files, strings or Pyana
URIs. The "style" argument may be None, in which case the source
XML file must contain a processing instruction.
If provided, "params" should be a dictionary containing
variable names as keys and XPaths as values.
The prefered means of calling this function is through keyword
arguments."""
t = Transformer()
t.setStylesheetParams(params)
return t.transform2File(source, style, file)
def transform2Writer(source, style, writer, params = {}):
"""transform2Writer(source, style, writer [, params ])
Transform the XML document specified by "source", using the XSLT
stylesheet specified by "style", writing to the file object given
in "writer".
The "source" and "style" arguments can be files, strings or Pyana
URIs. The "style" argument may be None, in which case the source
XML file must contain a processing instruction.
If provided, "params" should be a dictionary containing
variable names as keys and XPaths as values.
The prefered means of calling this function is through keyword
arguments."""
t = Transformer()
t.setStylesheetParams(params)
return t.transform2Writer(source, style, writer)
def transform2DOM(source, style, params = {}):
"""transform2DOM(source, style, [, params ])
Transform the XML document specified by "source", using the XSLT
stylesheet specified by "style", returning the output as a DOM.
The "source" and "style" arguments can be files, strings or Pyana
URIs. The "style" argument may be None, in which case the source
XML file must contain a processing instruction.
If provided, "params" should be a dictionary containing
variable names as keys and XPaths as values.
The prefered means of calling this function is through keyword
arguments."""
t = Transformer()
t.setStylesheetParams(params)
return t.transform2DOM(source, style)
class DefaultProblemListener:
"""This is the default class used by Pyana to report errors and
XSLT messages that occur during the XSLT transformation process."""
def problem(
self, where, classification,
sourceNode, styleNode,
msg, uri, line, offset):
import sys
typeMap = {
eERROR: 'Error: ',
eWARNING: 'Warning: ',
eMESSAGE: 'Message: ' }
sys.stdout.write(typeMap[classification])
sys.stdout.write(msg)
if uri or line != -1 or offset != -1:
if line != -1 or offset != -1:
sys.stdout.write(' ["%s" (%s, %s)]' % (uri, line, offset))
else:
sys.stdout.write(' ["%s"]'% (uri,))
sys.stdout.write("\n")
# This global variable determines which ProblemListner is used by
# Pyana to report errors and messages during XSLT transformation
defaultProblemListenerFactory = DefaultProblemListener
class DefaultErrorHandler:
"""This is the default class used by Pyana to report errors that
occur during the parsing of XML files."""
def common(self, name, e):
print '%s: %s' % (name, e.message),
if e.systemID or e.lineNumber or e.columnNumber:
print '["%s" (%s, %s)]' % (e.systemID, e.lineNumber, e.columnNumber)
else:
print
def warning(self, e):
self.common('Warning', e)
def error(self, e):
self.common('Error', e)
def fatalError(self, e):
self.common('FatalError', e)
raise e
def resetErrors(self):
pass
# This global variable determines which ErrorHandler is used by
# Pyana to report errors during XML parsing
defaultErrorHandlerFactory = DefaultErrorHandler
# These methods are used when repr is called on various Pyana
# objects
def _elemtemplateelement_repr(type_name, element):
if element is None:
return "<%s at %x; dead>" % (
type_name,
id(element),
)
return "<%s at %x: Name=%r at line %d, column %d>" % (
type_name,
id(element),
element.elementName,
element.lineNumber,
element.columnNumber)
def _node_repr(type_name, node):
if node is None:
return "<%s at %x; dead>" % (
type_name,
id(node),
)
if node.nodeType == ELEMENT_NODE:
return "<%s at %x: Name='%s' with %d children>" % (
type_name,
id(node),
node.nodeName,
len(node.childNodes)
)
else:
return "<%s at %x: Name='%s'>" % (
type_name, id(node),
node.nodeName
)
def _nodelist_repr(type_name, nodelist):
if nodelist is None:
return "<%s at %x; dead>" % (
type_name,
id(nodelist),
)
else:
return "<%s at %x: [%s]>" % (
type_name,
id(nodelist),
', '.join([repr(node) for node in nodelist])
)
_nodeset_repr = _nodelist_repr
def _tracerevent_repr(type_name, tracer_event):
if tracer_event is None:
return "<%s at %x; dead>" % (
type_name,
id(tracer_event),
)
return '<%s at %x>' % (type_name, id(tracer_event))
def _selectionevent_repr(type_name, selection_event):
if selection_event is None:
return "<%s at %x; dead>" % (
type_name,
id(selection_event),
)
return '<%s at %x>' % (type_name, id(selection_event))
def _generateevent_repr(type_name, generate_event):
if generate_event is None:
return "<%s at %x; dead>" % (
type_name,
id(generate_event),
)
eventName = None
for name, value in globals().items():
if (value == generate_event.eventType) and \
name.startswith('EVENTTYPE_'):
eventName = name
break
return '<%s at %x: eventType=%s>' % (type_name, id(generate_event), eventName or 'Unknown')
def _findTestFileInStack():
import sys
import os
for n in range(1000):
filename = os.path.basename(sys._getframe(n).f_code.co_filename)
if filename.startswith('Test'):
print
print '--->', filename, sys._getframe(n).f_lineno, '<----'
print
break
# Depreciated functions
def deprecation(message):
try:
import warnings
except ImportError:
import sys
print >> sys.stderr, 'DeprecationWarning:', message
else:
warnings.warn(message, DeprecationWarning, stacklevel=3)
def transformToString(source, style, params = {}):
"Depreciated, see transform2String"
deprecation(
'transformToString is depreciated, use transform2String instead')
return transform2String(source, style, params)
def transformToFile(source, style, file, params = {}):
"Depreciated, see transform2File"
deprecation(
'transformToFile is depreciated, use transform2File instead')
return transform2File(source, style, file, params)
def transformToWriter(source, style, writer, params = {}):
"Depreciated, see transform2Writer"
deprecation(
'transformToWriter is depreciated, use transform2Writer instead')
return transform2Writer(source, style, writer, params)
def install(ns, func, name):
"Depreciated, see installGlobalExtension"
deprecation(
'install is depreciated, use installGlobalExtension instead')
return installGlobalExtension(ns, func, name)
def installWithContext(ns, func, name):
"Depreciated, see installGlobalExtensionWithContext"
deprecation(
'installWithContext is depreciated, use '
'installGlobalExtensionWithContext instead')
return installGlobalExtensionWithContext(ns, func, name)
def remove(ns, name):
"Depreciated, see removeGlobalExtension"
deprecation(
'remove is depreciated, use '
'removeGlobalExtension instead')
return removeGlobalExtension(ns, name)
|