#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import urllib
from lxml import etree
def print_value(_, node, v):
'''A dummy function - just to test the variable'''
if isinstance(v, list):
return v[0]
else:
return v
def quote(_, s):
'''Encodes the input text to be used in URLs'''
if isinstance(s, unicode):
return urllib.quote(s.encode('utf-8'))
elif isinstance(s, etree._Element):
return urllib.quote(s.text)
elif isinstance(s, str):
return urllib.quote(s)
elif isinstance(s, list):
return quote(_, s[0])
else:
return urllib.quote(str(int(s)))
def main():
'''Test xsl:variable in external functions'''
ns = etree.FunctionNamespace('http://rambler.ru/fe')
ns.prefix = "fe"
ns['print_value'] = print_value
ns['quote'] = quote
style = etree.XML('''
42
trick
a=test
Not using a variable:
With a variable:
Not using a variable:
With a variable:
Not using a variable:
With a variable:
''')
transform = etree.XSLT(style)
data = etree.XML('''
A very long text a very long text a very long text a very long text a very long text a very long text a very long text a very long text a very long text
''')
result_tree = transform(data)
print etree.tounicode(result_tree, pretty_print=True)
print "lxml.etree: ", etree.LXML_VERSION
print "libxml used: ", etree.LIBXML_VERSION
print "libxml compiled: ", etree.LIBXML_COMPILED_VERSION
print "libxslt used: ", etree.LIBXSLT_VERSION
print "libxslt compiled: ", etree.LIBXSLT_COMPILED_VERSION
return 0
if __name__ == '__main__':
sys.exit(main())