Project

Profile

Help

How to connect?
Download (147 KB) Statistics
| Branch: | Tag: | Revision:

he / latest10 / hec / Saxon.C.API / python-saxon / saxonc.pyx @ 250c5839

1
"""@package saxonc
2
This documentation details the Python API for Saxon/C, which has been written in cython for Python3.
3

    
4
Saxon/C is a cross-compiled variant of Saxon from the Java platform to the C/C++ platform.
5
Saxon/C provides processing in XSLT 3.0, XQuery 3.0/3.1 and XPath 2.0/3.0/3.1, and Schema validation 1.0/1.1.
6
Main classes in Saxon/C Python API: PySaxonProcessor, PyXsltProcessor, PyXslt30Processor, PyXQueryProcessor, PySchemaValidator, PyXdmValue, PyXdmItem, PyXdmNode and PyXdmAtomicValue."""
7

    
8

    
9
# distutils: language = c++
10

    
11
cimport saxoncClasses
12

    
13
from libcpp cimport bool
14
from libcpp.string cimport string
15
from libcpp.map cimport map
16
from nodekind import *
17
from os.path import isfile
18

    
19
cdef const char * make_c_str(str str_value):
20
    if str_value is None:
21
        return NULL
22
    else:
23
        c_string = str_value.encode('UTF-8')
24
        return c_string
25

    
26
cdef str make_py_str(const char * c_value):
27
    ustring = c_value.decode('UTF-8') if c_value is not NULL else None
28
    return ustring    
29
   
30

    
31
cdef class PySaxonProcessor:
32
    """An SaxonProcessor acts as a factory for generating XQuery, XPath, Schema and XSLT compilers.
33
    This class is itself the context that needs to be managed (i.e. allocation & release)
34

    
35
    Example:
36
          with saxonc.PySaxonProcessor(license=False) as proc:
37
             print("Test Saxon/C on Python")
38
             print(proc.version)
39
             xdmAtomicval = proc.make_boolean_value(False)
40
             xslt30proc = proc.new_xslt30_processor()
41
    """
42
    cdef saxoncClasses.SaxonProcessor *thisptr      # hold a C++ instance which we're wrapping
43

    
44
    ##
45
    # The Constructor
46
    # @param license Flag that a license is to be used
47
    # @contextlib.contextmanager
48
    def __cinit__(self, config_file= None, license=False):
49
        """
50
        __cinit__(self, config_file=None, license=False)
51
        The constructor.
52

    
53
        Args:
54
            config_file (str): Construct a Saxon processor based upon an configuration file
55
            license(bool): Flag that a license is to be used. The Default is false.
56
            
57
        """
58
        cdef const char * c_str = NULL
59
        cdef bool l = license
60
        if config_file is not None:
61
            c_str = make_c_str(config_file)
62
            if c_str is not NULL:
63
                self.thisptr = new saxoncClasses.SaxonProcessor(c_str)
64
            else:
65
                raise Exception("Configuration file for SaxonProcessor is None")
66
        else:
67
            self.thisptr = new saxoncClasses.SaxonProcessor(l)
68
            
69
    def __dealloc__(self):
70
        """The destructor."""
71
        del self.thisptr
72

    
73
    def __enter__(self):
74
      """enter method for use with the keyword 'with' context"""
75
      return self
76

    
77
    def __exit__(self, exception_type, exception_value, traceback):
78
        """The exit method for the context PySaxonProcessor. Here we release the Jet VM resources.
79
        If we have more than one live PySaxonProcessor object the release() method has no effect.
80
        """
81
        self.thisptr.release()
82

    
83
    property version:
84
        """
85
        Get the Saxon Version.
86

    
87
        Getter:
88
            str: The Saxon version
89
        """
90
        def __get__(self):        
91
            cdef const char* c_string = self.thisptr.version()
92
            ustring = c_string.decode('UTF-8')
93
            return ustring
94

    
95

    
96
    def release(self):
97
        """
98
        release(self) 
99
        Clean up and destroy Java VM to release memory used."""
100

    
101
        self.thisptr.release()
102

    
103

    
104
    @property
105
    def cwd(self):
106
        """
107
        cwd Property represents the current working directorty
108

    
109
        :str: Get or set the current working directory"""
110
        cdef const char* c_string = self.thisptr.getcwd()
111
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
112
        return ustring
113

    
114

    
115
    def set_cwd(self, cwd):
116
         py_value_string = cwd.encode('UTF-8') if cwd is not None else None
117
         cdef char * c_str_ = py_value_string if cwd is not None else ""
118
         self.thisptr.setcwd(c_str_)
119
    
120

    
121
    def set_resources_directory(self, dir_):
122
        """
123
        Property to set or get resources directory 
124
        
125
        :str: A string of the resources directory which Saxon will use
126

    
127
        """
128
        py_value_string = dir_.encode('UTF-8') if dir_ is not None else None
129
        cdef char * c_str_ = py_value_string if dir_ is not None else ""
130
        self.thisptr.setResourcesDirectory(c_str_)
131

    
132
    @property
133
    def resources_directory(self):
134
        cdef const char* c_string = self.thisptr.getResourcesDirectory()
135
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
136
        return ustring
137
    
138
    def set_configuration_property(self, name, value):
139
        """
140
        set_configuration_property(self, name, value)
141
        Set configuration property specific to the processor in use.
142
        Properties set here are common across all processors. 
143

    
144
        Args:
145
            name (str): The name of the property
146
            value (str): The value of the property
147

    
148
        Example:
149
          'l': 'on' or 'off' - to enable the line number
150

    
151
        """
152
        py_name_string = name.encode('UTF-8') if name is not None else None
153
        cdef char * c_str_ = py_name_string if name is not None else ""
154
        py_value_string = value.encode('UTF-8') if value is not None else None
155
        cdef char * c_value_str_ = py_value_string if value is not None else ""
156
        self.thisptr.setConfigurationProperty(c_str_, c_value_str_)
157

    
158
    def clear_configuration_properties(self):
159
        """
160
        clear_configuration_properties(self)
161
        Clear the configurations properties in use by the processor 
162

    
163
        """
164
        self.thisptr.clearConfigurationProperties()
165

    
166
    @property
167
    def is_schema_aware(self):
168
        """
169
        is_schema_aware(self)
170
        Property to check if the processor is Schema aware. A licensed Saxon-EE/C product is schema aware 
171

    
172
        :bool: Indicate if the processor is schema aware, True or False otherwise
173
        """
174
        return self.thisptr.isSchemaAwareProcessor()
175

    
176

    
177
    def new_xslt_processor(self):
178
        """
179
        new_xslt_processor(self)
180
        Create an PyXsltProcessor. A PyXsltProcessor is used to compile and execute XSLT stylesheets. 
181

    
182
        Returns: 
183
            PyXsltProcessor: a newly created PyXsltProcessor
184

    
185
        """
186
        cdef PyXsltProcessor val = PyXsltProcessor()
187
        val.thisxptr = self.thisptr.newXsltProcessor()
188
        return val
189

    
190
    def new_xslt30_processor(self):
191
        """
192
        new_xslt30_processor(self)
193
        Create an PyXslt30Processor. A PyXslt30Processor is used to compile and execute XSLT 3.0 stylesheets. 
194

    
195
        Returns: 
196
            PyXslt30Processor: a newly created PyXslt30Processor
197

    
198
        """
199
        cdef PyXslt30Processor val = PyXslt30Processor()
200
        val.thisxptr = self.thisptr.newXslt30Processor()
201
        return val
202

    
203
    def new_xquery_processor(self):
204
        """
205
        new_xquery_processor(self)
206
        Create an PyXqueryProcessor. A PyXQueryProcessor is used to compile and execute XQuery queries. 
207

    
208
        Returns: 
209
            PyXQueryProcessor: a newly created PyXQueryProcessor
210

    
211
        """
212
        cdef PyXQueryProcessor val = PyXQueryProcessor()
213
        val.thisxqptr = self.thisptr.newXQueryProcessor()
214
        return val
215

    
216
    def new_xpath_processor(self):
217
        """
218
        new_xpath_processor(self)
219
        Create an PyXPathProcessor. A PyXPathProcessor is used to compile and execute XPath expressions. 
220

    
221
        Returns: 
222
            PyXPathProcessor: a newly created XPathProcessor
223

    
224
        """
225
        cdef PyXPathProcessor val = PyXPathProcessor()
226
        val.thisxpptr = self.thisptr.newXPathProcessor()
227
        return val
228

    
229
    def new_schema_validator(self):
230
        """
231
        new_schema_validator(self)
232
        Create a PySchemaValidator which can be used to validate instance documents against the schema held by this 
233

    
234
        Returns: 
235
            PySchemaValidator: a newly created PySchemaValidator
236

    
237
        """
238
        cdef PySchemaValidator val = PySchemaValidator()
239
        val.thissvptr = self.thisptr.newSchemaValidator()
240
        if val.thissvptr is NULL:
241
            raise Exception("Error: Saxon Processor is not licensed for schema processing!")
242
        return val
243

    
244
    def make_string_value(self, str_):
245
        """
246
        make_string_value(self, str_)
247
        Factory method. Unlike the constructor, this avoids creating a new StringValue in the case
248
        of a zero-length string (and potentially other strings, in future)
249
        
250
        Args:
251
            str_ (str): the String value. Null is taken as equivalent to "".
252

    
253
        Returns:
254
            PyXdmAtomicValue: The corresponding Xdm StringValue
255

    
256
        """
257
        py_value_string = str_.encode('UTF-8') if str_ is not None else None
258
        cdef char * c_str_ = py_value_string if str_ is not None else ""
259
        cdef PyXdmAtomicValue val = PyXdmAtomicValue()
260
        val.derivedaptr = val.derivedptr = val.thisvptr = self.thisptr.makeStringValue(c_str_)
261
        return val
262

    
263
    def make_integer_value(self, value):
264
        """
265
        make_integer_value(self, value)
266
        Factory method: makes either an Int64Value or a BigIntegerValue depending on the value supplied
267
        
268
        Args:
269
            value (int): The supplied primitive integer value
270

    
271
        Returns:
272
            PyXdmAtomicValue: The corresponding Xdm value which is a BigIntegerValue or Int64Value as appropriate
273

    
274
        """
275
        cdef PyXdmAtomicValue val = PyXdmAtomicValue()
276
        val.derivedaptr = val.derivedptr = val.thisvptr = self.thisptr.makeIntegerValue(value)
277
        return val
278

    
279
    def make_double_value(self, value):
280
        """
281
        make_double_value(self, value)
282
        Factory method: makes a double value
283

    
284
        Args:
285
            value (double): The supplied primitive double value 
286

    
287
        Returns:
288
            PyXdmAtomicValue: The corresponding Xdm Value
289
        """
290
        cdef PyXdmAtomicValue val = PyXdmAtomicValue()
291
        val.derivedaptr = val.derivedptr = val.thisvptr = self.thisptr.makeDoubleValue(value)
292
        return val
293

    
294
    def make_float_value(self, value):
295
        """
296
        make_float_value(self, value)
297
        Factory method: makes a float value
298

    
299
        Args:
300
            value (float): The supplied primitive float value 
301

    
302
        Returns:
303
            PyXdmAtomicValue: The corresponding Xdm Value
304
        """
305

    
306
        cdef PyXdmAtomicValue val = PyXdmAtomicValue()
307
        val.derivedaptr = val.derivedptr = val.thisvptr = self.thisptr.makeFloatValue(value)
308
        return val
309

    
310
    def make_long_value(self, value):
311
        """
312
        make_long_value(self, value)
313
        Factory method: makes either an Int64Value or a BigIntegerValue depending on the value supplied
314

    
315
        Args:
316
            value (long): The supplied primitive long value 
317

    
318
        Returns:
319
            PyXdmAtomicValue: The corresponding Xdm Value
320
        """
321
        cdef PyXdmAtomicValue val = PyXdmAtomicValue()
322
        val.derivedaptr = val.derivedptr = val.thisvptr = self.thisptr.makeLongValue(value)
323
        return val
324

    
325
    def make_boolean_value(self, value):
326
        """
327
        make_boolean_value(self, value)
328
        Factory method: makes a XdmAtomicValue representing a boolean Value
329

    
330
        Args:
331
            value (boolean): True or False, to determine which boolean value is required
332

    
333
        Returns:
334
            PyAtomicValue: The corresonding XdmValue
335
        """
336
        cdef bool c_b = value
337
        cdef PyXdmAtomicValue val = PyXdmAtomicValue()
338
        val.derivedaptr = val.derivedptr = val.thisvptr = self.thisptr.makeBooleanValue(c_b)
339
        return val
340

    
341
    def make_qname_value(self, str_):
342
        """
343
        make_qname_value(self, str_)
344
        Create an QName Xdm value from string representation in clark notation
345

    
346
        Args:
347
            str_ (str): The value given in a string form in clark notation. {uri}local
348

    
349
        Returns:
350
            PyAtomicValue: The corresonding value
351

    
352
        """
353
        py_value_string = str_.encode('UTF-8') if str_ is not None else None
354
        cdef char * c_str_ = py_value_string if str_ is not None else ""
355
        cdef PyXdmAtomicValue val = PyXdmAtomicValue()
356
        val.derivedaptr = val.derivedptr = val.thisvptr = self.thisptr.makeQNameValue(c_str_)
357
        return val
358

    
359
    def make_atomic_value(self, value_type, value):
360
        """
361
        make_atomic_value(self, value_type, value)
362
        Create an QName Xdm value from string representation in clark notation
363

    
364
        Args:
365
            str_ (str): The value given in a string form in clark notation. {uri}local
366

    
367
        Returns:
368
            PyAtomicValue: The corresonding value
369

    
370
        """
371

    
372
        py_valueType_string = value_type.encode('UTF-8') if value_type is not None else None
373
        cdef char * c_valueType_string = py_valueType_string if value_type is not None else ""
374
        cdef PyXdmAtomicValue val = PyXdmAtomicValue()
375
        val.derivedaptr = val.derivedptr = val.thisvptr = self.thisptr.makeAtomicValue(c_valueType_string, value)
376
        return val
377

    
378
    def get_string_value(self, PyXdmItem item):
379
        """
380
        get_string_value(self, PyXdmItem item)
381
        Create an QName Xdm value from string representation in clark notation
382

    
383
        Args:
384
            str_ (str): The value given in a string form in clark notation. {uri}local
385

    
386
        Returns:
387
            PyAtomicValue: The corresonding value
388

    
389
        """
390
        return self.thisptr.getStringValue(item.derivedptr)
391

    
392
    def parse_xml(self, **kwds):
393
        """
394
        parse_xml(self, **kwds)
395
        Parse a lexical representation, source file or uri of the source document and return it as an Xdm Node
396

    
397
        Args:
398
            **kwds : The possible keyword arguments must be one of the follow (xml_file_name|xml_text|xml_uri)
399

    
400
        Returns:
401
            PyXdmNode: The Xdm Node representation of the XML document
402

    
403
        Raises:
404
            Exception: Error if the keyword argument is not one of xml_file_name|xml_text|xml_uri.
405
        """
406
        py_error_message = "Error: parseXml should only contain one of the following keyword arguments: (xml_file_name|xml_text|xml_uri)"
407
        if len(kwds) != 1:
408
          raise Exception(py_error_message)
409
        cdef PyXdmNode val = None
410
        cdef py_value = None
411
        cdef char * c_xml_string = NULL
412
        if "xml_text" in kwds:
413
          py_value = kwds["xml_text"]
414
          py_xml_text_string = py_value.encode('UTF-8') if py_value is not None else None
415
          c_xml_string = py_xml_text_string if py_value is not None else "" 
416
          val = PyXdmNode()
417
          val.derivednptr = val.derivedptr = val.thisvptr = self.thisptr.parseXmlFromString(c_xml_string)
418
          return val
419
        elif "xml_file_name" in kwds:
420
          py_value = kwds["xml_file_name"]
421
          py_filename_string = py_value.encode('UTF-8') if py_value is not None else None
422
          if py_filename_string  is None or isfile(py_filename_string) == False:
423
            raise Exception("XML file does not exist")
424
          c_xml_string = py_filename_string if py_value is not None else ""
425
          val = PyXdmNode()
426
          val.derivednptr = val.derivedptr = val.thisvptr = self.thisptr.parseXmlFromFile(c_xml_string)
427
          return val 
428
        elif "xml_uri" in kwds:
429
          py_value = kwds["xml_uri"]
430
          py_uri_string = py_value.encode('UTF-8') if py_value is not None else None
431
          c_xml_string = py_uri_string if py_value is not None else ""
432
          val = PyXdmNode()
433
          val.derivednptr = val.derivedptr = val.thisvptr = self.thisptr.parseXmlFromUri(c_xml_string)
434
          return val
435
        else:
436
           raise Exception(py_error_message)
437

    
438
    def exception_occurred(self):
439
        """
440
        exception_occurred(self)
441
        Check if an exception has occurred internally within Saxon/C
442

    
443
        Returns:
444
            boolean: True or False if an exception has been reported internally in Saxon/C
445
        """
446
        return self.thisptr.exceptionOccurred()
447

    
448
    def exception_clear(self):
449
        """
450
        exceltion_clear(self)
451
        Clear any exception thrown internally in Saxon/C.
452

    
453

    
454
        """
455
        self.thisptr.exceptionClear()
456

    
457

    
458
cdef class PyXsltProcessor:
459
     """An PyXsltProcessor represents factory to compile, load and execute a stylesheet.
460
     It is possible to cache the context and the stylesheet in the PyXsltProcessor """
461

    
462
     cdef saxoncClasses.XsltProcessor *thisxptr      # hold a C++ instance which we're wrapping
463

    
464
     def __cinit__(self):
465
        """Default constructor """
466
        self.thisxptr = NULL
467
     def __dealloc__(self):
468
        if self.thisxptr != NULL:
469
           del self.thisxptr
470
     def set_cwd(self, cwd):
471
        """
472
        set_cwd(self, cwd)
473
        Set the current working directory.
474

    
475
        Args:
476
            cwd (str): current working directory
477
        """
478
        py_cwd_string = cwd.encode('UTF-8') if cwd is not None else None
479
        cdef char * c_cwd = py_cwd_string if cwd is not None else "" 
480
        self.thisxptr.setcwd(c_cwd)
481

    
482

    
483
     def set_base_output_uri(self, base_uri):
484
        """
485
        set_base_output_uri(self, base_uri)
486
        Set the base output URI. The default is the base URI of the principal output
487
        of the transformation. If a base output URI is supplied using this function then it takes precedence
488
        over any base URI defined in the principal output, and
489
        it may cause the base URI of the principal output to be modified in situ.
490
        The base output URI is used for resolving relative URIs in the 'href' attribute
491
        of the xsl:result-document instruction; it is accessible to XSLT stylesheet
492
        code using the XPath {@code current-output-uri()} function.
493

    
494
        Args:
495
            base_uri (str): the base output URI
496
        """
497
        py_uri_string = base_uri.encode('UTF-8') if base_uri is not None else None
498
        cdef char * c_uri = py_uri_string if base_uri is not None else ""
499
        self.thisxptr.setBaseOutputURI(c_uri)
500

    
501
     def set_source(self, **kwds):
502
        """Set the source document for the transformation.
503

    
504
        Args:
505
            **kwds: Keyword argument can only be one of the following: file_name|xdm_node
506
        Raises:
507
            Exception: Exception is raised if keyword argument is not one of file_name or node.
508
        """
509

    
510
        py_error_message = "Error: setSource should only contain one of the following keyword arguments: (file_name|xdm_node)"
511
        if len(kwds) != 1:
512
          raise Exception(py_error_message)
513
        cdef py_value = None
514
        cdef py_value_string = None
515
        cdef char * c_source
516
        cdef PyXdmNode xdm_node = None
517
        if "file_name" in kwds:
518
            py_value = kwds["file_name"]
519
            py_value_string = py_value.encode('UTF-8') if py_value is not None else None
520
            c_source = py_value_string if py_value is not None else "" 
521
            self.thisxptr.setSourceFromFile(c_source)
522
        elif "xdm_node" in kwds:
523
            xdm_node = kwds["xdm_node"]
524
            self.thisxptr.setSourceFromXdmNode(xdm_node.derivednptr)
525
        else:
526
          raise Exception(py_error_message)
527

    
528
     def set_output_file(self, output_file):
529
        """
530
        set_output_file(self, output_file)
531
        Set the output file where the output of the transformation will be sent
532

    
533
        Args:
534
            output_file (str): The output file supplied as a str
535

    
536
        """
537
        py_filename_string = output_file.encode('UTF-8') if output_file is not None else None
538
        cdef char * c_outputfile = py_filename_string if output_file is not None else ""
539
        self.thisxptr.setOutputFile(c_outputfile)
540

    
541
     def set_jit_compilation(self, bool jit):
542
        """
543
        set_jit_compilation(self, jit)
544
        Say whether just-in-time compilation of template rules should be used.
545

    
546
        Args:
547
            jit (bool): True if just-in-time compilation is to be enabled. With this option enabled,
548
                static analysis of a template rule is deferred until the first time that the
549
                template is matched. This can improve performance when many template
550
                rules are rarely used during the course of a particular transformation; however,
551
                it means that static errors in the stylesheet will not necessarily cause the
552
                compile(Source) method to throw an exception (errors in code that is
553
                actually executed will still be notified but this may happen after the compile(Source)
554
                method returns). This option is enabled by default in Saxon-EE, and is not available
555
                in Saxon-HE or Saxon-PE.
556
                Recommendation: disable this option unless you are confident that the
557
                stylesheet you are compiling is error-free. 
558

    
559
        """
560
        cdef bool c_jit
561
        c_jit = jit
562
        self.thisxptr.setJustInTimeCompilation(c_jit)
563
        #else:
564
        #raise Warning("setJustInTimeCompilation: argument must be a boolean type. JIT not set")
565
     def set_parameter(self, name, PyXdmValue value):
566
        """
567
        set_parameter(self, PyXdmValue value)
568
        Set the value of a stylesheet parameter
569

    
570
        Args:
571
            name (str): the name of the stylesheet parameter, as a string. For namespaced parameter use the JAXP solution i.e. "{uri}name
572
            value (PyXdmValue): the value of the stylesheet parameter, or null to clear a previously set value
573

    
574
        """
575
        cdef const char * c_str = make_c_str(name)
576
        if c_str is not NULL:
577
            value.thisvptr.incrementRefCount()
578
            self.thisxptr.setParameter(c_str, value.thisvptr)
579

    
580
     def get_parameter(self, name):
581
        """
582
        get_parameter(self, name)
583
        Get a parameter value by a given name
584

    
585
        Args:
586
            name (str): The name of the stylesheet parameter
587

    
588
        Returns:
589
            PyXdmValue: The Xdm value of the parameter  
590

    
591

    
592
        """
593
        py_name_string = name.encode('UTF-8') if name is not None else None
594
        cdef char * c_name = py_name_string if name is not None else ""
595
        cdef PyXdmValue val = PyXdmValue()
596
        val.thisvptr = self.thisxptr.getParameter(c_name)
597
        return val
598

    
599
     def remove_parameter(self, name):
600
        """
601
        remove_parameter(self, name)
602
        Remove the parameter given by name from the PyXsltProcessor. The parameter will not have any affect on the stylesheet if it has not yet been executed
603

    
604
        Args:
605
            name (str): The name of the stylesheet parameter
606

    
607
        Returns:
608
            bool: True if the removal of the parameter has been successful, False otherwise.
609

    
610
        """
611

    
612
        py_name_string = name.encode('UTF-8') if name is not None else None
613
        cdef char * c_name = py_name_string if name is not None else ""
614
        return self.thisxptr.removeParameter(c_name)
615

    
616
     def set_property(self, name, value):
617
        """
618
        set_property(self, name, value)
619
        Set a property specific to the processor in use.
620
 
621
        Args:
622
            name (str): The name of the property
623
            value (str): The value of the property
624

    
625
        Example:
626
            XsltProcessor: set serialization properties (names start with '!' i.e. name "!method" -> "xml")\r
627
            'o':outfile name,\r
628
            'it': initial template,\r 
629
            'im': initial mode,\r
630
            's': source as file name\r
631
            'm': switch on message listener for xsl:message instructions,\r
632
            'item'| 'node' : source supplied as an XdmNode object,\r
633
            'extc':Set the native library to use with Saxon for extension functions written in C/C++/PHP\r
634

    
635
        """
636

    
637
        py_name_string = name.encode('UTF-8') if name is not None else None
638
        cdef char * c_name = py_name_string if name is not None else ""
639
        py_value_string = value.encode('UTF-8') if value is not None else None
640
        cdef char * c_value = py_value_string if value is not None else ""
641
        self.thisxptr.setProperty(c_name, c_value)
642

    
643
     def clear_parameters(self):
644
        """
645
        clear_parameter(self)
646
        Clear all parameters set on the processor for execution of the stylesheet
647
        """
648

    
649
        self.thisxptr.clearParameters()
650
     def clear_properties(self):
651
        """
652
        clear_properties(self)
653
        Clear all properties set on the processor
654
        """
655

    
656
        self.thisxptr.clearProperties()
657

    
658
     def setup_xsl_message(self, show, file_name = None):
659
        """
660
        setup_xsl_message(self, **kwds)
661
        gives users the option to switch on or off the <code>xsl:message</code> feature. It is also possible
662
        to send the <code>xsl:message</code> outputs to file given by file name.
663

    
664
        """
665
        py_name_string = file_name.encode('UTF-8') if file_name is not None else None
666
        cdef char * c_file_name = py_name_string if file_name is not None else NULL
667
        self.thisxptr.getXslMessages(bool(show), c_file_name)
668

    
669

    
670
     def transform_to_string(self, **kwds):
671
        """
672
        transform_to_string(self, **kwds)
673
        Execute transformation to string.
674

    
675
        Args:
676
            **kwds: Possible arguments: source_file (str) or xdm_node (PyXdmNode). Other allowed argument: stylesheet_file (str)
677

    
678

    
679
        Example:
680

    
681
            1) result = xsltproc.transform_to_string(source_file="cat.xml", stylesheet_file="test1.xsl")
682

    
683
            2) xsltproc.set_source("cat.xml")\r
684
               result = xsltproc.transform_to_string(stylesheet_file="test1.xsl")
685

    
686

    
687
            3) node = saxon_proc.parse_xml(xml_text="<in/>")\r
688
               result = xsltproc.transform_to_string(stylesheet_file="test1.xsl", xdm_node= node)
689
        """
690

    
691
        cdef char * c_sourcefile
692
        cdef char * c_stylesheetfile
693
        py_source_string = None
694
        py_stylesheet_string = None
695
        for key, value in kwds.items():
696
          if isinstance(value, str):
697
            if key == "source_file":
698
              py_source_string = value.encode('UTF-8') if value is not None else None
699
              if py_source_string  is None or isfile(py_source_string) == False:
700
                raise Exception("source file name does not exist")
701
              c_sourcefile = py_source_string if value is not None else "" 
702
            if key == "stylesheet_file":
703
              py_stylesheet_string = value.encode('UTF-8') if value is not None else None
704
              if py_stylesheet_string  is None or isfile(py_stylesheet_string) == False:
705
                raise Exception("Stylesheet file does not exist")
706
              c_stylesheetfile = py_stylesheet_string if value is not None else ""
707
          elif key == "xdm_node":
708
            if isinstance(value, PyXdmNode):
709
              self.setSourceFromXdmNode(value)
710
          elif len(kwds) > 0:
711
            raise Warning("Warning: transform_to_string should only the following keyword arguments: (source_file, stylesheet_file, xdm_node)")
712

    
713
        cdef const char* c_string            
714
        if len(kwds) == 0:
715
          c_string = self.thisxptr.transformToString()
716
        else:     
717
          c_string = self.thisxptr.transformFileToString(c_sourcefile if py_source_string is not None else NULL, c_stylesheetfile if py_stylesheet_string is not None else NULL)
718

    
719
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
720
        return ustring
721

    
722
     def transform_to_file(self, **kwds):
723
        """
724
        transform_to_file(self, **kwds)
725
        Execute transformation to a file. It is possible to specify the as an argument or using the set_output_file method.       
726
        Args:
727
            **kwds: Possible optional arguments: source_file (str) or xdm_node (PyXdmNode). Other allowed argument: stylesheet_file (str), output_file (str)
728

    
729

    
730
        Example:
731

    
732
            1) xsltproc.transform_to_file(source_file="cat.xml", stylesheet_file="test1.xsl", output_file="result.xml")
733

    
734
            2) xsltproc.set_source("cat.xml")\r
735
               xsltproc.setoutput_file("result.xml")\r
736
               xsltproc.transform_to_file(stylesheet_file="test1.xsl")
737

    
738

    
739
            3) node = saxon_proc.parse_xml(xml_text="<in/>")\r
740
               xsltproc.transform_to_file(output_file="result.xml", stylesheet_file="test1.xsl", xdm_node= node)        
741
        """
742
        cdef char * c_sourcefile
743
        cdef char * c_outputfile
744
        cdef char * c_stylesheetfile
745
        py_source_string = None
746
        py_stylesheet_string = None
747
        py_output_string = None
748
        cdef PyXdmNode node_
749
        for key, value in kwds.items():
750
          if isinstance(value, str):
751
            if key == "source_file":
752
              py_source_string = value.encode('UTF-8') if value is not None else None
753
              c_sourcefile = py_source_string if value is not None else ""
754
            if key == "output_file":
755
              py_output_string = value.encode('UTF-8') if value is not None else None
756
              c_outputfile = py_output_string if value is not None else ""  
757
            if key == "stylesheet_file":
758
              py_stylesheet_string = value.encode('UTF-8') if value is not None else None
759
              c_stylesheetfile = py_stylesheet_string if value is not None else ""
760
          elif key == "xdm_node":
761
            if isinstance(value, PyXdmNode):
762
              node_ = value
763
              self.thisxptr.setSourceFromXdmNode(node_.derivednptr)
764
            
765
        if len(kwds) == 0:
766
          self.thisxptr.transformToFile()
767
        else:     
768
          self.thisxptr.transformFileToFile(c_sourcefile if py_source_string is not None else NULL, c_stylesheetfile if py_stylesheet_string is not None else NULL, c_outputfile if py_output_string is not None else NULL)
769

    
770

    
771
     def transform_to_value(self, **kwds):
772
        """
773
        transform_to_value(self, **kwds)
774
        Execute transformation to an Xdm Node
775

    
776
        Args:
777
            **kwds: Possible optional arguments: source_file (str) or xdm_node (PyXdmNode). Other allowed argument: stylesheet_file (str)
778

    
779

    
780

    
781
        Returns:
782
            PyXdmNode: Result of the transformation as an PyXdmNode object
783

    
784

    
785
        Example:
786

    
787
            1) node = xsltproc.transform_to_value(source_file="cat.xml", stylesheet_file="test1.xsl")
788

    
789
            2) xsltproc.set_source("cat.xml")\r
790
               node = xsltproc.transform_to_value(stylesheet_file="test1.xsl")
791

    
792

    
793
            3) node = saxon_proc.parse_xml(xml_text="<in/>")\r
794
               node = xsltproc.transform_tovalue(stylesheet_file="test1.xsl", xdm_node= node)        
795
        """
796
        cdef const char * c_sourcefile = NULL
797
        cdef const char * c_stylesheetfile = NULL
798
        py_source_string = None
799
        py_stylesheet_string = None
800
        for key, value in kwds.items():
801
          if isinstance(value, str):
802
            if key == "source_file":
803
              c_sourcefile = make_c_str(value)  
804
            if key == "stylesheet_file":
805
              c_stylesheetfile = make_c_str(value)
806
          elif key == "xdm_node":
807
            if isinstance(value, PyXdmNode):
808
              self.setSourceFromXdmNode(value)
809
        cdef PyXdmValue val = None
810
        cdef PyXdmAtomicValue aval = None
811
        cdef PyXdmNode nval = None
812
        cdef saxoncClasses.XdmValue * xdmValue = NULL
813
        if len(kwds) == 0:
814
          xdmValue = self.thisxptr.transformToValue()
815
        else:     
816
          xdmValue = self.thisxptr.transformFileToValue(c_sourcefile, c_stylesheetfile)
817

    
818
        if xdmValue is NULL:
819
            return None        
820
        cdef type_ = xdmValue.getType()
821
        if type_== 4:
822
            aval = PyXdmAtomicValue()
823
            aval.derivedaptr = aval.derivedptr = aval.thisvptr = <saxoncClasses.XdmAtomicValue *>xdmValue
824
            return aval        
825
        elif type_ == 3:
826
            nval = PyXdmNode()        
827
            nval.derivednptr = nval.derivedptr = nval.thisvptr = <saxoncClasses.XdmNode*>xdmValue
828
            return nval
829
        else:
830
            val = PyXdmValue()
831
            val.thisvptr = xdmValue
832
            return val
833

    
834
     def compile_stylesheet(self, **kwds):
835
        """
836
        compile_stylesheet(self, **kwds)
837
        Compile a stylesheet  received as text, uri or as a node object. The compiled stylesheet is cached and available for execution
838
        later. It is also possible to save the compiled stylesheet (SEF file) given the option 'save' and 'output_file'
839
   
840
        Args:
841
            **kwds: Possible keyword arguments stylesheet_text (str), stylesheet_file (str) or stylsheetnode (PyXdmNode). Also possible
842
                    to add the options save (boolean), static_base_uri (str) and output_file (str), which creates an exported stylesheet to file (SEF).
843
                    The static_base_uri keyword argument can only be used with stylesheet_text. The base URI is part of the static context, and is used to
844
                    resolve any relative URIs appearing within an XPath expression.
845

    
846
        Example:
847
            1. xsltproc.compile_stylesheet(stylesheet_text="<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>
848
            <xsl:param name='values' select='(2,3,4)' /><xsl:output method='xml' indent='yes' /><xsl:template match='*'><output>
849
              <xsl:value-of select='//person[1]'/>
850
              <xsl:for-each select='$values' >
851
                <out><xsl:value-of select='. * 3'/></out>
852
              </xsl:for-each></output></xsl:template>
853
            </xsl:stylesheet>")
854

    
855
            2. xsltproc.compile_stylesheet(stylesheet_file="test1.xsl", save=True, output_file="test1.sef")
856
        """
857
        py_error_message = "CompileStylesheet should only be one of the keyword option: (stylesheet_text|stylesheet_file|stylesheet_node), also allowed in addition the optional keyword 'save' boolean with the keyword 'outputfile' keyword"
858
        if len(kwds) >3:
859
          raise Exception(py_error_message)
860
        cdef char * c_outputfile
861
        cdef char * c_stylesheet
862
        py_output_string = None
863
        py_stylesheet_string = None
864
        py_save = False
865
        cdef int option = 0
866
        cdef PyXdmNode py_xdmNode = None
867
        if kwds.keys() >= {"stylesheet_text", "stylesheet_file"}:
868
          raise Exception(py_error_message)
869
        if kwds.keys() >= {"stylesheet_text", "stylesheet_node"}:
870
          raise Exception(py_error_message)
871
        if kwds.keys() >= {"stylesheet_node", "stylesheet_file"}:
872
          raise Exception(py_error_message)
873

    
874
        if ("save" in kwds) and kwds["save"]==True:
875
          del kwds["save"]
876
          if "output_file" not in kwds:
877
            raise Exception("Output file option not in keyword arugment for compile_stylesheet")
878
          py_output_string = kwds["output_file"].encode('UTF-8')
879
          c_outputfile = py_output_string
880
          if "stylesheet_text" in kwds:
881
            if "static_base_uri" in kwds:
882
              py_baseuri_string = kwds["static_base_uri"].encode('UTF-8')
883
              c_baseuri = py_baseuri_string
884
              self.thisxptr.setcwd(c_baseuri)
885
            py_stylesheet_string = kwds["stylesheet_text"].encode('UTF-8')
886
            c_stylesheet = py_stylesheet_string
887
            self.thisxptr.compileFromStringAndSave(c_stylesheet, c_outputfile)
888
          elif "stylesheet_file" in kwds:
889
            py_stylesheet_string = kwds["stylesheet_file"].encode('UTF-8')
890
            c_stylesheet = py_stylesheet_string
891
            self.thisxptr.compileFromFileAndSave(c_stylesheet, c_outputfile)
892
          elif "stylesheet_node" in kwds:
893
            py_xdmNode = kwds["stylesheet_node"]
894
            #if not isinstance(py_value, PyXdmNode):
895
              #raise Exception("StylesheetNode keyword arugment is not of type XdmNode")
896
            #value = PyXdmNode(py_value)
897
            self.thisxptr.compileFromXdmNodeAndSave(py_xdmNode.derivednptr, c_outputfile)
898
          else:
899
            raise Exception(py_error_message)
900
        else:
901
          if "stylesheet_text" in kwds:
902
            py_stylesheet_string = kwds["stylesheet_text"].encode('UTF-8')
903
            c_stylesheet = py_stylesheet_string
904
            if "static_base_uri" in kwds:
905
              py_baseuri_string = kwds["static_base_uri"].encode('UTF-8')
906
              c_baseuri = py_baseuri_string
907
              self.thisxptr.setcwd(c_baseuri)
908
            self.thisxptr.compileFromString(c_stylesheet)
909
          elif "stylesheet_file" in kwds:
910
            py_stylesheet_string = kwds["stylesheet_file"].encode('UTF-8')
911
            c_stylesheet = py_stylesheet_string
912
            self.thisxptr.compileFromFile(c_stylesheet)
913
          elif "stylesheet_node" in kwds:
914
            py_xdmNode = kwds["stylesheet_node"]
915
            #if not isinstance(py_value, PyXdmNode):
916
              #raise Exception("StylesheetNode keyword arugment is not of type XdmNode")
917
            #value = PyXdmNode(py_value)
918
            self.thisxptr.compileFromXdmNode(py_xdmNode.derivednptr)
919
          else:
920
            raise Exception(py_error_message)
921

    
922
     def release_stylesheet(self):
923
        """
924
        release_stylesheet(self)
925
        Release cached stylesheet
926

    
927
        """
928
        self.thisxptr.releaseStylesheet()
929

    
930
     def exception_occurred(self):
931
        """
932
        exception_occurred(self)
933
        Checks for pending exceptions without creating a local reference to the exception object
934
        Returns:
935
            boolean: True when there is a pending exception; otherwise return False        
936

    
937
        """
938
        return self.thisxptr.exceptionCount() >0
939

    
940
     def check_exception(self):
941
        """
942
        check_exception(self)
943
        Check for exception thrown and get message of the exception.
944
  
945
        Returns:
946
            str: Returns the exception message if thrown otherwise return None
947

    
948
        """
949
        cdef const char* c_string = self.thisxptr.checkException()
950
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
951
        return ustring
952

    
953
     def exception_clear(self):
954
        """
955
        exception_clear(self)
956
        Clear any exception thrown
957

    
958
        """
959
        self.thisxptr.exceptionClear()
960

    
961
     def exception_count(self):
962
        """
963
        excepton_count(self)
964
        Get number of errors reported during execution.
965

    
966
        Returns:
967
            int: Count of the exceptions thrown during execution
968
        """
969
        return self.thisxptr.exceptionCount()
970

    
971
     def get_error_message(self, index):
972
        """
973
        get_error_message(self, index)
974
        A transformation may have a number of errors reported against it. Get the ith error message if there are any errors
975

    
976
        Args:
977
            index (int): The i'th exception
978
        
979
        Returns:
980
            str: The message of the i'th exception. Return None if the i'th exception does not exist.
981
        """
982
        cdef const char* c_string = self.thisxptr.getErrorMessage(index)
983
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
984
        return ustring
985

    
986
     def get_error_code(self, index):
987
        """
988
        get_error_code(self, index)
989
        A transformation may have a number of errors reported against it. Get the i'th error code if there are any errors
990

    
991
        Args:
992
            index (int): The i'th exception
993
        
994
        Returns:
995
            str: The error code associated with the i'th exception. Return None if the i'th exception does not exist.
996

    
997
        """
998
        cdef const char* c_string = self.thisxptr.getErrorCode(index)
999
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
1000
        return ustring
1001

    
1002
parametersDict = None
1003

    
1004
cdef class PyXslt30Processor:
1005
     """An PyXslt30Processor represents factory to compile, load and execute a stylesheet.
1006
     It is possible to cache the context and the stylesheet in the PyXslt30Processor """
1007

    
1008
     cdef saxoncClasses.Xslt30Processor *thisxptr      # hold a C++ instance which we're wrapping
1009

    
1010

    
1011
     def __cinit__(self):
1012
        """Default constructor """
1013
        self.thisxptr = NULL
1014
     def __dealloc__(self):
1015
        if self.thisxptr != NULL:
1016
           del self.thisxptr
1017
     def set_cwd(self, cwd):
1018
        """
1019
        set_cwd(self, cwd)
1020
        Set the current working directory.
1021

    
1022
        Args:
1023
            cwd (str): current working directory
1024
        """
1025
        py_cwd_string = cwd.encode('UTF-8') if cwd is not None else None
1026
        cdef char * c_cwd = py_cwd_string if cwd is not None else ""
1027
        self.thisxptr.setcwd(c_cwd)
1028

    
1029
     def set_base_output_uri(self, base_uri):
1030
        """
1031
        set_base_output_uri(self, base_uri)
1032
        Set the base output URI. The default is the base URI of the principal output
1033
        of the transformation. If a base output URI is supplied using this function then it takes precedence
1034
        over any base URI defined in the principal output, and
1035
        it may cause the base URI of the principal output to be modified in situ.
1036
        The base output URI is used for resolving relative URIs in the 'href' attribute
1037
        of the xsl:result-document instruction; it is accessible to XSLT stylesheet
1038
        code using the XPath {@code current-output-uri()} function.
1039

    
1040
        Args:
1041
            base_uri (str): the base output URI
1042
        """
1043
        py_uri_string = base_uri.encode('UTF-8') if base_uri is not None else None
1044
        cdef char * c_uri = py_uri_string if base_uri is not None else ""
1045
        self.thisxptr.setBaseOutputURI(c_uri)
1046

    
1047
     def set_global_context_item(self, **kwds):
1048
        """Set the global context item for the transformation.
1049

    
1050
        Args:
1051
            **kwds: Keyword argument can only be one of the following: file_name|xdm_item
1052
        Raises:
1053
            Exception: Exception is raised if keyword argument is not one of file_name or an Xdm item.
1054
        """
1055

    
1056
        py_error_message = "Error: set_global_context_item should only contain one of the following keyword arguments: (file_name|xdm_item)"
1057
        if len(kwds) != 1:
1058
          raise Exception(py_error_message)
1059
        cdef py_value = None
1060
        cdef py_value_string = None
1061
        cdef char * c_source
1062
        cdef PyXdmItem xdm_item = None
1063
        if "file_name" in kwds:
1064
            py_value = kwds["file_name"]
1065
            py_value_string = py_value.encode('UTF-8') if py_value is not None else None
1066
            c_source = py_value_string if py_value is not None else ""
1067
            self.thisxptr.setGlobalContextFromFile(c_source)
1068
        elif "xdm_item" in kwds:
1069
            if isinstance(kwds["xdm_item"], PyXdmItem):
1070
                xdm_item = kwds["xdm_item"]
1071
                self.thisxptr.setGlobalContextItem(xdm_item.derivedptr)
1072
            else:
1073
                raise Exception("xdm_item value must be of type PyXdmItem")
1074
        else:
1075
          raise Exception(py_error_message)
1076

    
1077
     def set_initial_match_selection(self, **kwds):
1078
        """
1079
        set_initial_match_selection(self, **kwds)
1080
        The initial filename to which templates are to be applied (equivalent to the <code>select</code> attribute of <code>xsl:apply-templates</code>).
1081

    
1082
        Args:
1083
            **kwds: Keyword argument can only be one of the following: file_name|xdm_value
1084
        Raises:
1085
            Exception: Exception is raised if keyword argument is not one of file_name or XdmValue.
1086
        """
1087

    
1088
        py_error_message = "Error: set_initial_match_selection should only contain one of the following keyword arguments: (file_name|xdm_value)"
1089
        if len(kwds) != 1:
1090
          raise Exception(py_error_message)
1091
        cdef py_value = None
1092
        cdef py_value_string = None
1093
        cdef char * c_source
1094
        cdef PyXdmValue xdm_value = None
1095
        if "file_name" in kwds:
1096
            py_value = kwds["file_name"]
1097
            py_value_string = py_value.encode('UTF-8') if py_value is not None else None
1098
            c_source = py_value_string if py_value is not None else ""
1099
            self.thisxptr.setInitialMatchSelectionAsFile(c_source)
1100
        elif "xdm_value" in kwds:
1101
            xdm_value = kwds["xdm_value"]
1102
            self.thisxptr.setInitialMatchSelection(xdm_value.thisvptr)
1103
        else:
1104
          raise Exception(py_error_message)
1105

    
1106
     def set_output_file(self, output_file):
1107
        """
1108
        set_output_file(self, output_file)
1109
        Set the output file where the output of the transformation will be sent
1110

    
1111
        Args:
1112
            output_file (str): The output file supplied as a str
1113

    
1114
        """
1115
        py_filename_string = output_file.encode('UTF-8') if output_file is not None else None
1116
        cdef char * c_outputfile = py_filename_string if output_file is not None else ""
1117
        self.thisxptr.setOutputFile(c_outputfile)
1118

    
1119
     def set_jit_compilation(self, bool jit):
1120
        """
1121
        set_jit_compilation(self, jit)
1122
        Say whether just-in-time compilation of template rules should be used.
1123

    
1124
        Args:
1125
            jit (bool): True if just-in-time compilation is to be enabled. With this option enabled,
1126
                static analysis of a template rule is deferred until the first time that the
1127
                template is matched. This can improve performance when many template
1128
                rules are rarely used during the course of a particular transformation; however,
1129
                it means that static errors in the stylesheet will not necessarily cause the
1130
                compile(Source) method to throw an exception (errors in code that is
1131
                actually executed will still be notified but this may happen after the compile(Source)
1132
                method returns). This option is enabled by default in Saxon-EE, and is not available
1133
                in Saxon-HE or Saxon-PE.
1134
                Recommendation: disable this option unless you are confident that the
1135
                stylesheet you are compiling is error-free.
1136

    
1137
        """
1138
        cdef bool c_jit
1139
        c_jit = jit
1140
        self.thisxptr.setJustInTimeCompilation(c_jit)
1141
        #else:
1142
        #raise Warning("setJustInTimeCompilation: argument must be a boolean type. JIT not set")
1143

    
1144

    
1145
     def set_result_as_raw_value(self, bool is_raw):
1146
        """
1147
        set_result_as_raw_value(self, is_raw)
1148
        Set true if the return type of callTemplate, applyTemplates and transform methods is to return XdmValue, otherwise return XdmNode object with root Document node
1149

    
1150
        Args:
1151
            is_raw (bool): True if returning raw result, i.e. XdmValue, otherwise return XdmNode
1152

    
1153
        """
1154
        cdef bool c_raw
1155
        c_raw = is_raw
1156
        self.thisxptr.setResultAsRawValue(c_raw)
1157
        #else:
1158
        #raise Warning("setJustInTimeCompilation: argument must be a boolean type. JIT not set")
1159

    
1160
     def set_parameter(self, name, PyXdmValue value):
1161
        """
1162
        set_parameter(self, PyXdmValue value)
1163
        Set the value of a stylesheet parameter
1164

    
1165
        Args:
1166
            name (str): the name of the stylesheet parameter, as a string. For namespaced parameter use the JAXP solution i.e. "{uri}name
1167
            value (PyXdmValue): the value of the stylesheet parameter, or null to clear a previously set value
1168

    
1169
        """
1170
        cdef const char * c_str = make_c_str(name)
1171
        if c_str is not NULL:
1172
            '''value.thisvptr.incrementRefCount()
1173
            print("set_parameter called")'''
1174
            self.thisxptr.setParameter(c_str, value.thisvptr, False)
1175

    
1176
     def get_parameter(self, name):
1177
        """
1178
        get_parameter(self, name)
1179
        Get a parameter value by a given name
1180

    
1181
        Args:
1182
            name (str): The name of the stylesheet parameter
1183

    
1184
        Returns:
1185
            PyXdmValue: The Xdm value of the parameter
1186

    
1187

    
1188
        """
1189
        py_name_string = name.encode('UTF-8') if name is not None else None
1190
        cdef char * c_name = py_name_string if name is not None else ""
1191
        cdef PyXdmValue val = PyXdmValue()
1192
        val.thisvptr = self.thisxptr.getParameter(c_name)
1193
        return val
1194

    
1195
     def remove_parameter(self, name):
1196
        """
1197
        remove_parameter(self, name)
1198
        Remove the parameter given by name from the PyXslt30Processor. The parameter will not have any affect on the stylesheet if it has not yet been executed
1199

    
1200
        Args:
1201
            name (str): The name of the stylesheet parameter
1202

    
1203
        Returns:
1204
            bool: True if the removal of the parameter has been successful, False otherwise.
1205

    
1206
        """
1207

    
1208
        py_name_string = name.encode('UTF-8') if name is not None else None
1209
        cdef char * c_name = py_name_string if name is not None else ""
1210
        return self.thisxptr.removeParameter(c_name)
1211

    
1212
     def set_property(self, name, value):
1213
        """
1214
        set_property(self, name, value)
1215
        Set a property specific to the processor in use.
1216

    
1217
        Args:
1218
            name (str): The name of the property
1219
            value (str): The value of the property
1220

    
1221
        Example:
1222
            XsltProcessor: set serialization properties (names start with '!' i.e. name "!method" -> "xml")\r
1223
            'o':outfile name,\r
1224
            'it': initial template,\r
1225
            'im': initial mode,\r
1226
            's': source as file name\r
1227
            'm': switch on message listener for xsl:message instructions,\r
1228
            'item'| 'node' : source supplied as an XdmNode object,\r
1229
            'extc':Set the native library to use with Saxon for extension functions written in C/C++/PHP\r
1230

    
1231
        """
1232

    
1233
        py_name_string = name.encode('UTF-8') if name is not None else None
1234
        cdef char * c_name = py_name_string if name is not None else ""
1235
        py_value_string = value.encode('UTF-8') if value is not None else None
1236
        cdef char * c_value = py_value_string if value is not None else ""
1237
        self.thisxptr.setProperty(c_name, c_value)
1238

    
1239
     def clear_parameters(self):
1240
        """
1241
        clear_parameter(self)
1242
        Clear all parameters set on the processor for execution of the stylesheet
1243
        """
1244

    
1245
        self.thisxptr.clearParameters()
1246
     def clear_properties(self):
1247
        """
1248
        clear_properties(self)
1249
        Clear all properties set on the processor
1250
        """
1251

    
1252
        self.thisxptr.clearProperties()
1253

    
1254

    
1255
     def set_initial_template_parameters(self, bool tunnel, dict kwds):
1256
        """
1257
        set_initial_template_parameters(self, bool tunnel, **kwds)
1258
        Set parameters to be passed to the initial template. These are used
1259
        whether the transformation is invoked by applying templates to an initial source item,
1260
        or by invoking a named template. The parameters in question are the xsl:param elements
1261
        appearing as children of the xsl:template element.
1262

    
1263
        TODO: To fix issue where we pass XdmValue object created directly in the function argument. This causes seg error
1264
        e.g. set_initial_template_parameter(False, {a:saxonproc.make_integer_value(12)})
1265
        Do the following instead:
1266
        paramArr = {a:saxonproc.make_integer_value(12)}
1267
        set_initial_template_parameter(False, paramArr)
1268

    
1269
        Args:
1270
        	tunnel (bool): True if these values are to be used for setting tunnel parameters;
1271
        	**kwds: the parameters to be used for the initial template supplied as an key-value pair.
1272
        	False if they are to be used for non-tunnel parameters. The default is false.
1273

    
1274
        Example:
1275

    
1276
        	1)paramArr = {'a':saxonproc.make_integer_value(12), 'b':saxonproc.make_integer_value(5)} 
1277
                  xsltproc.set_initial_template_parameters(False, paramArr)
1278
        """
1279
        cdef map[string, saxoncClasses.XdmValue * ] parameters
1280
        cdef bool c_tunnel
1281
        cdef string key_str
1282
        c_tunnel = tunnel
1283
        cdef PyXdmAtomicValue value_
1284
        global parametersDict
1285
        if kwds is not None:
1286
                parametersDict = kwds
1287
        for (key, value) in kwds.items():
1288
                if isinstance(value, PyXdmAtomicValue):
1289
                        value_ = value
1290
                        key_str = key.encode('UTF-8')
1291
                        value_.derivedptr.incrementRefCount()
1292
                        parameters[key_str] = <saxoncClasses.XdmValue *> value_.derivedaptr
1293
                else:
1294
                        raise Exception("Initial template parameters can only be of type PyXdmValue")
1295
        if len(kwds) > 0:
1296
            self.thisxptr.setInitialTemplateParameters(parameters, c_tunnel);
1297

    
1298
     def setup_xsl_message(self, show, str file_name = None):
1299
        """
1300
        setup_xsl_message(self, **kwds)
1301
        gives users the option to switch on or off the <code>xsl:message</code> feature. It is also possible
1302
        to send the <code>xsl:message</code> outputs to file given by file name.
1303

    
1304
        """
1305
        py_name_string = file_name.encode('UTF-8') if file_name is not None else None
1306
        cdef char * c_file_name = py_name_string if file_name is not None else NULL
1307
        self.thisxptr.getXslMessages(show, c_file_name)
1308

    
1309
     def transform_to_string(self, **kwds):
1310
        """
1311
        transform_to_string(self, **kwds)
1312
        Execute transformation to string.
1313

    
1314
        Args:
1315
            **kwds: Possible arguments: source_file (str) or xdm_node (PyXdmNode). Other allowed argument: stylesheet_file (str)
1316
                                        and base_output_uri (str) which is used for for resolving relative URIs in the href
1317
                                        attribute of the xsl:result-document instruction.
1318

    
1319

    
1320
        Example:
1321

    
1322
            1) result = xsltproc.transform_to_string(source_file="cat.xml", stylesheet_file="test1.xsl")
1323

    
1324
            2) xsltproc.set_source("cat.xml")\r
1325
               result = xsltproc.transform_to_string(stylesheet_file="test1.xsl")
1326

    
1327

    
1328
            3) node = saxon_proc.parse_xml(xml_text="<in/>")\r
1329
               result = xsltproc.transform_to_string(stylesheet_file="test1.xsl", xdm_node= node)
1330
        """
1331

    
1332
        cdef char * c_sourcefile
1333
        cdef char * c_stylesheetfile
1334
        py_source_string = None
1335
        py_stylesheet_string = None
1336
        cdef PyXdmNode node_ = None
1337
        for key, value in kwds.items():
1338
          if isinstance(value, str):
1339
            if key == "source_file":
1340
              py_source_string = value.encode('UTF-8') if value is not None else None
1341
              c_sourcefile = py_source_string if value is not None else ""
1342
            if key == "base_output_uri":
1343
              c_base_output_uri = make_c_str(value)
1344
              self.thisxptr.setBaseOutputURI(c_base_output_uri)
1345
            if key == "stylesheet_file":
1346
              py_stylesheet_string = value.encode('UTF-8') if value is not None else None
1347
              c_stylesheetfile = py_stylesheet_string if value is not None else ""
1348
          elif key == "xdm_node":
1349
            if isinstance(value, PyXdmNode):
1350
              node_ = value
1351
          elif len(kwds) > 0:
1352
            raise Warning("Warning: transform_to_string should only contain the following keyword arguments: (source_file|xdm_node, stylesheet_file)")
1353

    
1354
        cdef const char* c_string
1355
        if node_ is not None:
1356
          if py_stylesheet_string is not None:
1357
            self.thisxptr.compileFromFile(c_stylesheetfile)
1358
          c_string = self.thisxptr.transformToString(node_.derivednptr)
1359
        else:
1360
          c_string = self.thisxptr.transformFileToString(c_sourcefile if py_source_string is not None else NULL, c_stylesheetfile if py_stylesheet_string is not None else NULL)
1361

    
1362
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
1363
        return ustring
1364

    
1365
     def transform_to_file(self, **kwds):
1366
        """
1367
        transform_to_file(self, **kwds)
1368
        Execute transformation to a file. It is possible to specify the as an argument or using the set_output_file method.
1369
        Args:
1370
            **kwds: Possible optional arguments: source_file (str) or xdm_node (PyXdmNode). Other allowed argument: stylesheet_file (str), output_file (str)
1371
                                                 and base_output_uri (str) which is used for for resolving relative URIs in the href attribute of the
1372
                                                 xsl:result-document instruction.
1373

    
1374
        Example:
1375

    
1376
            1) xsltproc.transform_to_file(source_file="cat.xml", stylesheet_file="test1.xsl", output_file="result.xml")
1377

    
1378
            2) xsltproc.set_source("cat.xml")\r
1379
               xsltproc.setoutput_file("result.xml")\r
1380
               xsltproc.transform_to_file(stylesheet_file="test1.xsl")
1381

    
1382

    
1383
            3) node = saxon_proc.parse_xml(xml_text="<in/>")\r
1384
               xsltproc.transform_to_file(output_file="result.xml", stylesheet_file="test1.xsl", xdm_node= node)
1385
        """
1386
        cdef char * c_sourcefile
1387
        cdef char * c_outputfile
1388
        cdef char * c_stylesheetfile
1389
        py_source_string = None
1390
        py_stylesheet_string = None
1391
        py_output_string = None
1392
        cdef PyXdmNode node_ = None
1393
        for key, value in kwds.items():
1394
                if isinstance(value, str):
1395
                        if key == "source_file":
1396
                                py_source_string = value.encode('UTF-8') if value is not None else None
1397
                                c_sourcefile = py_source_string if value is not None else ""
1398
                        if key == "base_output_uri":
1399
                                c_base_output_uri = make_c_str(value)
1400
                                self.thisxptr.setBaseOutputURI(c_base_output_uri)
1401
                        if key == "output_file":
1402
                                py_output_string = value.encode('UTF-8') if value is not None else None
1403
                                c_outputfile = py_output_string if value is not None else ""
1404
                        if key == "stylesheet_file":
1405
                                py_stylesheet_string = value.encode('UTF-8') if value is not None else None
1406
                                c_stylesheetfile = py_stylesheet_string if value is not None else ""
1407
                        elif key == "xdm_node":
1408
                                if isinstance(value, PyXdmNode):
1409
                                        node_ = value
1410
              
1411
        if node_ is not None:
1412
                if py_output_string is not None:
1413
                        self.thisxptr.setOutputFile(c_outputfile);
1414
                self.thisxptr.transformToFile(node_.derivednptr)
1415
        else:
1416
                self.thisxptr.transformFileToFile(c_sourcefile if py_source_string is not None else NULL, c_stylesheetfile if py_stylesheet_string is not None else NULL, c_outputfile if py_output_string is not None else NULL)
1417

    
1418

    
1419
     def transform_to_value(self, **kwds):
1420
        """
1421
        transform_to_value(self, **kwds)
1422
        Execute transformation to an Xdm Node
1423

    
1424
        Args:
1425
            **kwds: Possible optional arguments: source_file (str) or xdm_node (PyXdmNode). Other allowed argument: stylesheet_file (str)
1426
                                                 and base_output_uri (str) which is used for for resolving relative URIs in the href attribute
1427
                                                 of the xsl:result-document instruction.
1428

    
1429

    
1430

    
1431
        Returns:
1432
            PyXdmNode: Result of the transformation as an PyXdmNode object
1433

    
1434

    
1435
        Example:
1436

    
1437
            1) node = xsltproc.transform_to_value(source_file="cat.xml", stylesheet_file="test1.xsl")
1438

    
1439
            2) xsltproc.set_source("cat.xml")\r
1440
               node = xsltproc.transform_to_value(stylesheet_file="test1.xsl")
1441

    
1442

    
1443
            3) node = saxon_proc.parse_xml(xml_text="<in/>")\r
1444
               node = xsltproc.transform_tovalue(stylesheet_file="test1.xsl", xdm_node= node)
1445
        """
1446
        cdef const char * c_sourcefile = NULL
1447
        cdef const char * c_stylesheetfile = NULL
1448
        cdef PyXdmNode node_ = None
1449
        py_source_string = None
1450
        py_stylesheet_string = None
1451
        for key, value in kwds.items():
1452
          if isinstance(value, str):
1453
            if key == "source_file":
1454
              c_sourcefile = make_c_str(value)
1455
            if key == "base_output_uri":
1456
              c_base_output_uri = make_c_str(value)
1457
              self.thisxptr.setBaseOutputURI(c_base_output_uri)
1458
            if key == "stylesheet_file":
1459
              c_stylesheetfile = make_c_str(value)
1460
          elif key == "xdm_node":
1461
            if isinstance(value, PyXdmNode):
1462
              node_ = value
1463
        cdef PyXdmValue val = None
1464
        cdef PyXdmAtomicValue aval = None
1465
        cdef PyXdmNode nval = None
1466
        cdef saxoncClasses.XdmValue * xdmValue = NULL
1467
        if len(kwds) == 1 and node_ is not None:
1468
          xdmValue = self.thisxptr.transformToValue(node_.derivednptr)
1469
        else:
1470
          xdmValue = self.thisxptr.transformFileToValue(c_sourcefile, c_stylesheetfile)
1471

    
1472
        if xdmValue is NULL:
1473
            return None
1474
        cdef type_ = xdmValue.getType()
1475
        if type_== 4:
1476
            aval = PyXdmAtomicValue()
1477
            aval.derivedaptr = aval.derivedptr = aval.thisvptr = <saxoncClasses.XdmAtomicValue *>xdmValue
1478
            return aval
1479
        elif type_ == 3:
1480
            nval = PyXdmNode()
1481
            nval.derivednptr = nval.derivedptr = nval.thisvptr = <saxoncClasses.XdmNode*>xdmValue
1482
            return nval
1483
        else:
1484
            val = PyXdmValue()
1485
            val.thisvptr = xdmValue
1486
            return val
1487

    
1488
     def apply_templates_returning_value(self, **kwds):
1489
        """
1490
        apply_templates_returning_value(self, **kwds)
1491
        Invoke the stylesheet by applying templates to a supplied input sequence, Saving the results as an XdmValue.
1492

    
1493
        Args:
1494
            **kwds: Possible optional arguments: source_file (str) or xdm_value (PyXdmValue). Other allowed argument: stylesheet_file (str) and
1495
                                                 base_output_uri (str) which is used for for resolving relative URIs in the href attribute of
1496
                                                 the xsl:result-document instruction.
1497

    
1498

    
1499

    
1500
        Returns:
1501
            PyXdmValue: Result of the transformation as an PyXdmValue object
1502

    
1503

    
1504
        Example:
1505

    
1506
            1) xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1507
               node = xsltproc.apply_templates_returning_value(stylesheet_file="test1.xsl")
1508

    
1509

    
1510
            2) xsltproc.compile_stylesheet(stylesheet_file="test1.xsl")
1511
			   xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1512
               node = xsltproc.apply_templates_returning_value()
1513

    
1514
        """
1515
        cdef const char * c_sourcefile = NULL
1516
        cdef const char * c_stylesheetfile = NULL
1517
        cdef PyXdmValue value_ = None
1518
        py_source_string = None
1519
        py_stylesheet_string = None
1520
        for key, value in kwds.items():
1521
          if isinstance(value, str):
1522
            if key == "source_file":
1523
              c_sourcefile = make_c_str(value)
1524
              self.thisxptr.setInitialMatchSelectionAsFile(c_sourcefile)
1525
            if key == "base_output_uri":
1526
              c_base_output_uri = make_c_str(value)
1527
              self.thisxptr.setBaseOutputURI(c_base_output_uri)
1528
            if key == "stylesheet_file":
1529
              c_stylesheetfile = make_c_str(value)
1530
          elif key == "xdm_value":
1531
            if isinstance(value, PyXdmValue):
1532
              value_ = value;
1533
              self.thisxptr.setInitialMatchSelection(value_.thisvptr)
1534
        cdef PyXdmValue val = None
1535
        cdef PyXdmAtomicValue aval = None
1536
        cdef PyXdmNode nval = None
1537
        cdef saxoncClasses.XdmValue * xdmValue = NULL
1538
        xdmValue = self.thisxptr.applyTemplatesReturningValue(c_stylesheetfile)
1539

    
1540
        if xdmValue is NULL:
1541
            return None
1542
        cdef type_ = xdmValue.getType()
1543
        if type_== 4:
1544
            aval = PyXdmAtomicValue()
1545
            aval.derivedaptr = aval.derivedptr = aval.thisvptr = <saxoncClasses.XdmAtomicValue *>xdmValue
1546
            return aval
1547
        elif type_ == 3:
1548
            nval = PyXdmNode()
1549
            nval.derivednptr = nval.derivedptr = nval.thisvptr = <saxoncClasses.XdmNode*>xdmValue
1550
            return nval
1551
        else:
1552
            val = PyXdmValue()
1553
            val.thisvptr = xdmValue
1554
            return val
1555

    
1556

    
1557
     def apply_templates_returning_string(self, **kwds):
1558
        """
1559
        apply_templates_returning_string(self, **kwds)
1560
        Invoke the stylesheet by applying templates to a supplied input sequence, Saving the results as a str.
1561

    
1562
        Args:
1563
            **kwds: Possible optional arguments: source_file (str) or xdm_value (PyXdmValue). Other allowed argument: stylesheet_file (str) and
1564
                                                 base_output_uri (str) which is used for for resolving relative URIs in the href attribute of
1565
                                                 the xsl:result-document instruction
1566

    
1567

    
1568

    
1569
        Returns:
1570
            PyXdmValue: Result of the transformation as an PyXdmValue object
1571

    
1572

    
1573
        Example:
1574

    
1575
            1) xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1576
               content = xsltproc.apply_templates_returning_str(stylesheet_file="test1.xsl")
1577
			   print(content)
1578

    
1579
        """
1580
        cdef const char * c_sourcefile = NULL
1581
        cdef const char * c_stylesheetfile = NULL
1582
        cdef PyXdmValue value_ = None
1583
        py_source_string = None
1584
        py_stylesheet_string = None
1585
        for key, value in kwds.items():
1586
          if isinstance(value, str):
1587
            if key == "source_file":
1588
              c_sourcefile = make_c_str(value)
1589
              self.thisxptr.setInitialMatchSelectionAsFile(c_sourcefile)
1590
            if key == "base_output_uri":
1591
              c_base_output_uri = make_c_str(value)
1592
              self.thisxptr.setBaseOutputURI(c_base_output_uri)
1593
            if key == "stylesheet_file":
1594
              c_stylesheetfile = make_c_str(value)
1595
          elif key == "xdm_value":
1596
            if isinstance(value, PyXdmValue):
1597
              value_ = value;
1598
              self.thisxptr.setInitialMatchSelection(value_.thisvptr)
1599
        cdef const char* c_string  = self.thisxptr.applyTemplatesReturningString(c_stylesheetfile) 
1600
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
1601
        return ustring
1602

    
1603
     def apply_templates_returning_file(self, **kwds):
1604
        """
1605
        apply_templates_returning_file(self, **kwds)
1606
        Invoke the stylesheet by applying templates to a supplied input sequence, Saving the 
1607
        results to file.
1608

    
1609
        Args:
1610
            **kwds: Possible optional arguments: source_file (str) or xdm_value (PyXdmValue). 
1611
            Other allowed argument: stylesheet_file (str) and the required argument output_file (str),
1612
            base_output_uri (str) which is used for for resolving relative URIs in the href attribute of
1613
            the xsl:result-document instruction.
1614

    
1615

    
1616
        Returns:
1617
            PyXdmValue: Result of the transformation as an PyXdmValue object
1618

    
1619

    
1620
        Example:
1621

    
1622
            1) xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1623
               content = xsltproc.apply_templates_returning_file(stylesheet_file="test1.xsl", output_file="result.xml")
1624
			   print(content)
1625

    
1626
        """
1627
        cdef const char * c_sourcefile = NULL
1628
        cdef const char * c_stylesheetfile = NULL
1629
        cdef const char * c_outputfile = NULL
1630
        cdef PyXdmValue value_ = None
1631
        py_source_string = None
1632
        py_stylesheet_string = None
1633
        py_output_string = None
1634
        for key, value in kwds.items():
1635
          if isinstance(value, str):
1636
            if key == "source_file":
1637
              c_sourcefile = make_c_str(value)
1638
              self.thisxptr.setInitialMatchSelectionAsFile(c_sourcefile)
1639
            if key == "base_output_uri":
1640
              c_base_output_uri = make_c_str(value)
1641
              self.thisxptr.setBaseOutputURI(c_base_output_uri)
1642
            if key == "output_file":
1643
              py_output_string = value.encode('UTF-8') if value is not None else None
1644
              c_outputfile = py_output_string if value is not None else ""
1645
            if key == "stylesheet_file":
1646
              c_stylesheetfile = make_c_str(value)
1647
          elif key == "xdm_value":
1648
            if isinstance(value, PyXdmNode):
1649
              value_ = value;
1650
              self.thisxptr.setInitialMatchSelection(value_.thisvptr)
1651
        self.thisxptr.applyTemplatesReturningFile(c_stylesheetfile, c_outputfile) 
1652
        
1653

    
1654
     def call_template_returning_value(self, str template_name=None, **kwds):
1655
        """
1656
        call_template_returning_value(self, str template_name, **kwds)
1657
        Invoke a transformation by calling a named template and return result as an PyXdmValue.
1658

    
1659
        Args:
1660
			template_name(str): The name of the template to invoke. If None is supplied then call the initial-template
1661
            **kwds: Possible optional arguments: source_file (str) or xdm_value (PyXdmValue). Other allowed argument: stylesheet_file (str),
1662
                    base_output_uri (str) which is used for for resolving relative URIs in the href attribute of the xsl:result-document instruction
1663

    
1664

    
1665
        Returns:
1666
            PyXdmValue: Result of the transformation as an PyXdmValue object
1667

    
1668

    
1669
        Example:
1670
            1) node = xsltproc.call_template_returning_value("main", stylesheet_file="test1.xsl")
1671

    
1672

    
1673
            2) xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1674
               node = xsltproc.call_template_returning_value("main", stylesheet_file="test1.xsl")
1675

    
1676

    
1677
            3) xsltproc.compile_stylesheet(stylesheet_file="test2.xsl")
1678
			   xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1679
               node = xsltproc.call_template_returning_value("go")
1680

    
1681
        """
1682
        cdef const char * c_templateName = NULL
1683
        cdef const char * c_sourcefile = NULL
1684
        cdef const char * c_stylesheetfile = NULL
1685
        cdef PyXdmValue value_ = None
1686
        py_source_string = None
1687
        py_template_name_str = None
1688
        py_stylesheet_string = None
1689
        for key, value in kwds.items():
1690
          if isinstance(value, str):
1691
            if key == "source_file":
1692
              c_sourcefile = make_c_str(value)
1693
              self.thisxptr.setInitialMatchSelectionAsFile(c_sourcefile)
1694
            if key == "base_output_uri":
1695
              c_base_output_uri = make_c_str(value)
1696
              self.thisxptr.setBaseOutputURI(c_base_output_uri)
1697
            if key == "stylesheet_file":
1698
              c_stylesheetfile = make_c_str(value)
1699
          elif key == "xdm_node":
1700
            if isinstance(value, PyXdmValue):
1701
              value_ = value;
1702
              self.thisxptr.setInitialMatchSelection(value_.thisvptr)
1703

    
1704
        c_templateName = make_c_str(template_name)
1705
        cdef PyXdmValue val = None
1706
        cdef PyXdmAtomicValue aval = None
1707
        cdef PyXdmNode nval = None
1708
        cdef saxoncClasses.XdmValue * xdmValue = NULL
1709
        xdmValue = self.thisxptr.callTemplateReturningValue(c_stylesheetfile, c_templateName)
1710

    
1711
        if xdmValue is NULL:
1712
            return None
1713
        cdef type_ = xdmValue.getType()
1714
        if type_== 4:
1715
            aval = PyXdmAtomicValue()
1716
            aval.derivedaptr = aval.derivedptr = aval.thisvptr = <saxoncClasses.XdmAtomicValue *>xdmValue
1717
            return aval
1718
        elif type_ == 3:
1719
            nval = PyXdmNode()
1720
            nval.derivednptr = nval.derivedptr = nval.thisvptr = <saxoncClasses.XdmNode*>xdmValue
1721
            return nval
1722
        else:
1723
            val = PyXdmValue()
1724
            val.thisvptr = xdmValue
1725
            return val
1726

    
1727

    
1728

    
1729
     def call_template_returning_string(self, str template_name=None, **kwds):
1730
        """
1731
        call_template_returning_string(self, str template_name, **kwds)
1732
        Invoke a transformation by calling a named template and return result as a string.
1733

    
1734
        Args:
1735
			template_name(str): The name of the template to invoke. If None is supplied then call the initial-template
1736
            **kwds: Possible optional arguments: source_file (str) or  xdm_Value (PyXdmValue). Other allowed argument: stylesheet_file (str)
1737
            base_output_uri (str) which is used for for resolving relative URIs in the href attribute of the xsl:result-document instruction
1738

    
1739

    
1740

    
1741
        Returns:
1742
            PyXdmValue: Result of the transformation as an PyXdmValue object
1743

    
1744

    
1745
        Example:
1746
            1) result = xsltproc.call_template_returning_string("main", stylesheet_file="test1.xsl")
1747

    
1748

    
1749
            2) xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1750
               result = xsltproc.call_template_returning_string("main", stylesheet_file="test1.xsl")
1751

    
1752
        cdef const char * c_templateName = NULL
1753

    
1754
            3) xsltproc.compile_stylesheet(stylesheet_file="test2.xsl")
1755
			   xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1756
               result = xsltproc.call_template_returning_string("go")
1757
			   print(result)
1758
        """
1759
        cdef const char * c_sourcefile = NULL
1760
        cdef const char * c_stylesheetfile = NULL
1761
        cdef PyXdmNode value_ = None
1762
        py_source_string = None
1763
        py_template_name_str = None
1764
        py_stylesheet_string = None
1765
        for key, value in kwds.items():
1766
          if isinstance(value, str):
1767
            if key == "source_file":
1768
              c_sourcefile = make_c_str(value)
1769
              self.thisxptr.setInitialMatchSelectionAsFile(c_sourcefile)
1770
            if key == "base_output_uri":
1771
              c_base_output_uri = make_c_str(value)
1772
              self.thisxptr.setBaseOutputURI(c_base_output_uri)
1773
            if key == "stylesheet_file":
1774
              c_stylesheetfile = make_c_str(value)
1775
          elif key == "xdm_value":
1776
            if isinstance(value, PyXdmValue):
1777
              value_ = value;
1778
              self.thisxptr.setInitialMatchSelection(value_.thisvptr)
1779

    
1780
        c_templateName = make_c_str(template_name)
1781
        cdef const char* c_string  = self.thisxptr.callTemplateReturningString(c_stylesheetfile, c_templateName) 
1782
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
1783
        return ustring
1784

    
1785

    
1786
     def call_template_returning_file(self, str template_name=None, **kwds):
1787
        """
1788
        call_template_returning_file(self, str template_name, **kwds)
1789
        Invoke a transformation by calling a named template and save result in a specified file.
1790

    
1791
        Args:
1792
			template_name(str): The name of the template to invoke. If None is supplied then call the initial-template
1793
            **kwds: Possible optional arguments: source_file (str) or xdm_node (PyXdmNode). Other allowed argument: stylesheet_file (str)
1794
                    base_output_uri (str) which is used for for resolving relative URIs in the href attribute of the xsl:result-document instruction
1795

    
1796

    
1797
        Returns:
1798
            PyXdmValue: Result of the transformation as an PyXdmValue object
1799

    
1800

    
1801
        Example:
1802
            1) xsltproc.call_template_returning_file("main", stylesheet_file="test1.xsl",  output_file="result.xml")
1803

    
1804

    
1805
            2) xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1806
               xsltproc.call_template_returning_file("main", stylesheet_file="test1.xsl", output_file="result.xml")
1807

    
1808

    
1809
            3) xsltproc.compile_stylesheet(stylesheet_file="test2.xsl")
1810
			   xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1811
               xsltproc.call_template_returning_file("go", output_file="result.xml")
1812
			   print(result)
1813
        """
1814
        cdef char * c_outputfile = NULL       
1815
        cdef const char * c_templateName = NULL
1816
        cdef const char * c_sourcefile = NULL
1817
        cdef const char * c_stylesheetfile = NULL
1818
        cdef PyXdmValue value_ = None
1819
        py_source_string = None
1820
        py_template_name_str = None
1821
        py_stylesheet_string = None
1822
        py_output_string = None
1823
        for key, value in kwds.items():
1824
          if isinstance(value, str):
1825
            if key == "source_file":
1826
              c_sourcefile = make_c_str(value)
1827
              self.thisxptr.setInitialMatchSelectionAsFile(c_sourcefile)
1828
            if key == "base_output_uri":
1829
              c_base_output_uri = make_c_str(value)
1830
              self.thisxptr.setBaseOutputURI(c_base_output_uri)
1831
            if key == "output_file":
1832
              py_output_string = value.encode('UTF-8') if value is not None else None
1833
              c_outputfile = py_output_string if value is not None else ""
1834
            if key == "stylesheet_file":
1835
              c_stylesheetfile = make_c_str(value)
1836
          elif key == "xdm_value":
1837
            if isinstance(value, PyXdmValue):
1838
              value_ = value;
1839
              self.thisxptr.setInitialMatchSelection(value_.thisvptr)
1840

    
1841
        c_templateName = make_c_str(template_name)
1842
        self.thisxptr.callTemplateReturningFile(c_stylesheetfile, c_templateName, c_outputfile)
1843

    
1844

    
1845

    
1846
     def call_function_returning_value(self, str function_name, list args, **kwds):
1847
        """
1848
        call_function_returning_value(self, str function_name, list args, **kwds)
1849
        Invoke a transformation by calling a named template and return result as an PyXdmValue.
1850

    
1851
        Args:
1852
			function_name(str): The name of the template to invoke. If None is supplied then call the initial-template
1853
			list args: Pointer array of XdmValue object - he values of the arguments to be supplied to the function.
1854
            **kwds: Possible optional arguments: source_file (str) or xdm_value (PyXdmValue). Other allowed argument: stylesheet_file (str)
1855

    
1856

    
1857

    
1858
        Returns:
1859
            PyXdmValue: Result of the transformation as an PyXdmValue object
1860

    
1861

    
1862
        Example:
1863
            1) node = xsltproc.call_function_returning_value("{http://localhost/example}func", stylesheet_file="test1.xsl")
1864

    
1865

    
1866
            2) xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1867
               value = xsltproc.call_function_returning_value("{http://localhost/test}add", stylesheet_file="test1.xsl")
1868

    
1869

    
1870
            3) xsltproc.compile_stylesheet(stylesheet_file="test2.xsl")
1871
			   xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1872
               value = xsltproc.call_function_returning_value("{http://exmaple.com}func1")
1873

    
1874
        """
1875
        cdef const char * c_functionName = NULL
1876
        cdef const char * c_sourcefile = NULL
1877
        cdef const char * c_stylesheetfile = NULL
1878
        cdef PyXdmValue value_ = None
1879
        py_source_string = None
1880
        py_template_name_str = None
1881
        py_stylesheet_string = None
1882
        for key, value in kwds.items():
1883
          if isinstance(value, str):
1884
            if key == "source_file":
1885
              c_sourcefile = make_c_str(value)
1886
              self.thisxptr.setInitialMatchSelectionAsFile(c_sourcefile)
1887
            if key == "stylesheet_file":
1888
              c_stylesheetfile = make_c_str(value)
1889
          elif key == "xdm_value":
1890
            if isinstance(value, PyXdmValue):
1891
              value_ = value;
1892
              self.thisxptr.setInitialMatchSelection(value_.thisvptr)
1893
        cdef int len_= 0;
1894
        len_ = len(args)
1895
        """ TODO handle memory when finished with XdmValues """
1896
        cdef saxoncClasses.XdmValue ** argumentV = self.thisxptr.createXdmValueArray(len_)
1897
        
1898
        for x in range(len(args)):
1899
          if isinstance(args[x], PyXdmValue):
1900
            value_ = args[x];
1901
            argumentV[x] = value_.thisvptr
1902
          else:
1903
            raise Exception("Argument value at position " , x , " is not an PyXdmValue. The following object found: ", type(args[x]))
1904

    
1905
        c_functionName = make_c_str(function_name)
1906
        cdef PyXdmValue val = None
1907
        cdef PyXdmAtomicValue aval = None
1908
        cdef PyXdmNode nval = None
1909
        cdef saxoncClasses.XdmValue * xdmValue = NULL
1910
        xdmValue = self.thisxptr.callFunctionReturningValue(c_stylesheetfile, c_functionName, argumentV, len(args))
1911

    
1912
        if xdmValue is NULL:
1913
          return None
1914
        cdef type_ = xdmValue.getType()
1915
        if type_== 4:
1916
          aval = PyXdmAtomicValue()
1917
          aval.derivedaptr = aval.derivedptr = aval.thisvptr = <saxoncClasses.XdmAtomicValue *>xdmValue
1918
          return aval
1919
        elif type_ == 3:
1920
          nval = PyXdmNode()
1921
          nval.derivednptr = nval.derivedptr = nval.thisvptr = <saxoncClasses.XdmNode*>xdmValue
1922
          return nval
1923
        else:
1924
          val = PyXdmValue()
1925
          val.thisvptr = xdmValue
1926
          return val
1927

    
1928

    
1929

    
1930
     def call_function_returning_string(self, str function_name, list args, **kwds):
1931
        """
1932
        call_function_returning_string(self, str function_name, list args, **kwds)
1933
        Invoke a transformation by calling a named template and return result as a serialized string.
1934

    
1935
        Args:
1936
			function_name(str): The name of the template to invoke. If None is supplied then call the initial-template
1937
			list args: Pointer array of XdmValue object - he values of the arguments to be supplied to the function.
1938
            **kwds: Possible optional arguments: source_file (str) or xdm_value (PyXdmValue). Other allowed argument: stylesheet_file (str)
1939

    
1940

    
1941

    
1942
        Returns:
1943
            str: Result of the transformation as an str value
1944

    
1945

    
1946
        Example:
1947
            1) result = xsltproc.call_function_returning_string("{http://localhost/example}func", stylesheet_file="test1.xsl")
1948

    
1949

    
1950
            2) xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1951
               result = xsltproc.call_function_returning_string("{http://localhost/test}add", stylesheet_file="test1.xsl")
1952

    
1953

    
1954
            3) xsltproc.compile_stylesheet(stylesheet_file="test2.xsl")
1955
			   xsltproc.set_initial_match_selection(file_name="cat.xml")\r
1956
               result = xsltproc.call_function_returning_string("{http://exmaple.com}func1")
1957

    
1958
        """
1959
        cdef const char * c_functionName = NULL
1960
        cdef const char * c_sourcefile = NULL
1961
        cdef const char * c_stylesheetfile = NULL
1962
        cdef PyXdmValue value_ = None
1963
        py_source_string = None
1964
        py_template_name_str = None
1965
        py_stylesheet_string = None
1966
        for key, value in kwds.items():
1967
          if isinstance(value, str):
1968
            if key == "source_file":
1969
              c_sourcefile = make_c_str(value)
1970
              self.thisxptr.setInitialMatchSelectionAsFile(c_sourcefile)
1971
            if key == "base_output_uri":
1972
              c_base_output_uri = make_c_str(value)
1973
              self.thisxptr.setBaseOutputURI(c_base_output_uri)
1974
            if key == "stylesheet_file":
1975
              c_stylesheetfile = make_c_str(value)
1976
              if isfile(value) == False:
1977
                raise Exception("Stylesheet file does not exist")
1978
          elif key == "xdm_value":
1979
            if isinstance(value, PyXdmValue):
1980
              value_ = value;
1981
              self.thisxptr.setInitialMatchSelection(value_.thisvptr)
1982
        cdef int _len = len(args)
1983
        """ TODO handle memory when finished with XdmValues """
1984
        cdef saxoncClasses.XdmValue ** argumentV = self.thisxptr.createXdmValueArray(_len)
1985

    
1986
        for x in range(len(args)):
1987
          if isinstance(args[x], PyXdmValue):
1988
            value_ = args[x]
1989
            argumentV[x] = value_.thisvptr
1990
          else:
1991
            raise Exception("Argument value at position ",x," is not an PyXdmValue")
1992

    
1993
        c_functionName = make_c_str(function_name)
1994
        cdef PyXdmValue val = None
1995
        cdef PyXdmAtomicValue aval = None
1996
        cdef PyXdmNode nval = None
1997
        cdef saxoncClasses.XdmValue * xdmValue = NULL
1998
        cdef const char* c_string = self.thisxptr.callFunctionReturningString(c_stylesheetfile, c_functionName, argumentV, len(args))
1999
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
2000
        return ustring
2001

    
2002

    
2003
     def call_function_returning_file(self, str function_name, list args, **kwds):
2004
        """
2005
        call_function_returning_file(self, str function_name, list args, **kwds)
2006
        Invoke a transformation by calling a named template and return result as an PyXdmValue.
2007

    
2008
        Args:
2009
			function_name(str): The name of the template to invoke. If None is supplied 
2010
                        then call the initial-template
2011
			list args: Pointer array of XdmValue object - he values of the arguments to be supplied to the function.
2012
            **kwds: Possible optional arguments: source_file (str) or xdm_value (PyXdmValue). Other allowed argument: stylesheet_file (str)
2013

    
2014

    
2015

    
2016
        Returns:
2017
            PyXdmValue: Result of the transformation as an PyXdmValue object
2018

    
2019

    
2020
        Example:
2021
            1)  xsltproc.set_output_file("result.xml")
2022
				xsltproc.call_function_returning_file("{http://localhost/example}func", stylesheet_file="test1.xsl")
2023

    
2024

    
2025
            2) xsltproc.set_initial_match_selection(file_name="cat.xml")\r
2026
               xsltproc.call_function_returning_file("{http://localhost/test}add", stylesheet_file="test1.xsl", output_file="result.xml")
2027

    
2028

    
2029
            3) xsltproc.compile_stylesheet(stylesheet_file="test2.xsl")
2030
			   xsltproc.set_initial_match_selection(file_name="cat.xml")\r
2031
               xsltproc.call_function_returning_file("{http://exmaple.com}func1", output_file="result.xml")
2032

    
2033
        """
2034
        cdef const char * c_functionName = NULL
2035
        cdef const char * c_sourcefile = NULL
2036
        cdef const char * c_outputfile = NULL
2037
        cdef const char * c_stylesheetfile = NULL
2038
        cdef PyXdmValue value_ = None
2039
        cdef PyXdmValue valueArgs_ = None
2040
        py_source_string = None
2041
        py_template_name_str = None
2042
        py_stylesheet_string = None
2043
        for key, value in kwds.items():
2044
          if isinstance(value, str):
2045
            if key == "source_file":
2046
              c_sourcefile = make_c_str(value)
2047
              self.thisxptr.setInitialMatchSelectionAsFile(c_sourcefile)
2048
            if key == "base_output_uri":
2049
              c_base_output_uri = make_c_str(value)
2050
              self.thisxptr.setBaseOutputURI(c_base_output_uri)
2051
            if key == "output_file":
2052
              py_output_string = value.encode('UTF-8') if value is not None else None
2053
              c_outputfile = py_output_string if value is not None else ""
2054
            if key == "stylesheet_file":
2055
              c_stylesheetfile = make_c_str(value)
2056
              if isfile(value) == False:
2057
                raise Exception("Stylesheet file does not exist")
2058
          elif key == "xdm_value":
2059
            if isinstance(value, PyXdmValue):
2060
              value_ = value;
2061
              self.thisxptr.setInitialMatchSelection(value_.thisvptr)
2062
        cdef int _len = len(args)
2063
        """ TODO handle memory when finished with XdmValues """
2064
        cdef saxoncClasses.XdmValue ** argumentV = self.thisxptr.createXdmValueArray(_len)
2065

    
2066
        for x in range(len(args)):
2067
          if isinstance(args[x], PyXdmValue):
2068
            value_ = args[x]
2069
            argumentV[x] = value_.thisvptr
2070
          else:
2071
            raise Exception("Argument value at position ",x," is not an PyXdmValue")
2072

    
2073
        c_functionName = make_c_str(function_name)
2074
        cdef PyXdmValue val = None
2075
        cdef PyXdmAtomicValue aval = None
2076
        cdef PyXdmNode nval = None
2077
        cdef saxoncClasses.XdmValue * xdmValue = NULL
2078
        self.thisxptr.callFunctionReturningFile(c_stylesheetfile, c_functionName, argumentV, len(args), c_outputfile)
2079
	
2080

    
2081
        
2082
     def compile_stylesheet(self, **kwds):
2083
        """
2084
        compile_stylesheet(self, **kwds)
2085
        Compile a stylesheet  received as text, uri or as a node object. The compiled stylesheet 
2086
        is cached and available for execution later. It is also possible to save the compiled 
2087
        stylesheet (SEF file) given the option 'save' and 'output_file'.
2088

    
2089
        Get the stylesheet associated via the xml-stylesheet processing instruction (see
2090
        http://www.w3.org/TR/xml-stylesheet/) with the document
2091
        document specified in the source parameter, and that match
2092
        the given criteria.  If there are several suitable xml-stylesheet
2093
        processing instructions, then the returned Source will identify
2094
        a synthesized stylesheet module that imports all the referenced
2095
        stylesheet module.
2096

    
2097
        Args:
2098
            **kwds: Possible keyword arguments stylesheet_text (str), stylesheet_file (str), 
2099
            associated_file (str) or stylsheet_node (PyXdmNode). Also possible to add the options 
2100
            save (boolean) and output_file, which creates an exported stylesheet to file (SEF).
2101

    
2102
        Example:
2103
            1. xsltproc.compile_stylesheet(stylesheet_text="<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>
2104
                                             <xsl:param name='values' select='(2,3,4)' /><xsl:output method='xml' indent='yes' />
2105
                                             <xsl:template match='*'><output><xsl:value-of select='//person[1]'/>
2106
                                             <xsl:for-each select='$values' >
2107
                                               <out><xsl:value-of select='. * 3'/></out>
2108
                                             </xsl:for-each></output></xsl:template></xsl:stylesheet>")
2109

    
2110
            2. xsltproc.compile_stylesheet(stylesheet_file="test1.xsl", save=True, output_file="test1.sef")
2111
            3. xsltproc.compile(associated_file="foo.xml")  
2112
        """
2113
        py_error_message = "CompileStylesheet should only be one of the keyword option: (associated_file|stylesheet_text|stylesheet_file|stylesheet_node), also in allowed in addition the optional keyword 'save' boolean with the keyword 'outputfile' keyword"
2114
        if len(kwds) >3:
2115
          raise Exception(py_error_message)
2116
        cdef char * c_outputfile
2117
        cdef char * c_stylesheet
2118
        py_output_string = None
2119
        py_stylesheet_string = None
2120
        py_save = False
2121
        cdef int option = 0
2122
        cdef PyXdmNode py_xdmNode = None
2123
        if kwds.keys() >= {"stylesheet_text", "stylesheet_file"}:
2124
          raise Exception(py_error_message)
2125
        if kwds.keys() >= {"stylesheet_text", "stylesheet_node"}:
2126
          raise Exception(py_error_message)
2127
        if kwds.keys() >= {"stylesheet_node", "stylesheet_file"}:
2128
          raise Exception(py_error_message)
2129

    
2130
        if ("save" in kwds) and kwds["save"]==True:
2131
          del kwds["save"]
2132
          if "output_file" not in kwds:
2133
            raise Exception("Output file option not in keyword arugment for compile_stylesheet")
2134
          py_output_string = kwds["output_file"].encode('UTF-8')
2135
          c_outputfile = py_output_string
2136
          if "stylesheet_text" in kwds:
2137
            py_stylesheet_string = kwds["stylesheet_text"].encode('UTF-8')
2138
            c_stylesheet = py_stylesheet_string
2139
            self.thisxptr.compileFromStringAndSave(c_stylesheet, c_outputfile)
2140
          elif "stylesheet_file" in kwds:
2141
            py_stylesheet_string = kwds["stylesheet_file"].encode('UTF-8')
2142
            if py_stylesheet_string  is None or isfile(py_stylesheet_string) == False:
2143
              raise Exception("Stylesheet file does not exist")
2144
            c_stylesheet = py_stylesheet_string
2145
            self.thisxptr.compileFromFileAndSave(c_stylesheet, c_outputfile)
2146
          elif "stylesheet_node" in kwds:
2147
            py_xdmNode = kwds["stylesheet_node"]
2148
            #if not isinstance(py_value, PyXdmNode):
2149
              #raise Exception("StylesheetNode keyword arugment is not of type XdmNode")
2150
            #value = PyXdmNode(py_value)
2151
            self.thisxptr.compileFromXdmNodeAndSave(py_xdmNode.derivednptr, c_outputfile)
2152
          else:
2153
            raise Exception(py_error_message)
2154
        else:
2155
          if "stylesheet_text" in kwds:
2156
            py_stylesheet_string = kwds["stylesheet_text"].encode('UTF-8')
2157
            c_stylesheet = py_stylesheet_string
2158
            self.thisxptr.compileFromString(c_stylesheet)
2159
          elif "stylesheet_file" in kwds:
2160
            py_stylesheet_string = kwds["stylesheet_file"].encode('UTF-8')
2161
            c_stylesheet = py_stylesheet_string
2162
            if py_stylesheet_string  is None or isfile(py_stylesheet_string) == False:
2163
              raise Exception("Stylesheet file does not exist")
2164
            self.thisxptr.compileFromFile(c_stylesheet)
2165
          elif "associated_file" in kwds:
2166
            py_stylesheet_string = kwds["associated_file"].encode('UTF-8')
2167
            if py_stylesheet_string  is None or isfile(py_stylesheet_string) == False:
2168
              raise Exception("Stylesheet file does not exist")
2169
            c_stylesheet = py_stylesheet_string
2170
            self.thisxptr.compileFromAssociatedFile(c_stylesheet)
2171
          elif "stylesheet_node" in kwds:
2172
            py_xdmNode = kwds["stylesheet_node"]
2173
            #if not isinstance(py_value, PyXdmNode):
2174
              #raise Exception("StylesheetNode keyword arugment is not of type XdmNode")
2175
            #value = PyXdmNode(py_value)
2176
            self.thisxptr.compileFromXdmNode(py_xdmNode.derivednptr)
2177
          else:
2178
            raise Exception(py_error_message)
2179

    
2180

    
2181
  
2182
     def release_stylesheet(self):
2183
        """
2184
        release_stylesheet(self)
2185
        Release cached stylesheet
2186

    
2187
        """
2188
        self.thisxptr.releaseStylesheet()
2189

    
2190
     def exception_occurred(self):
2191
        """
2192
        exception_occurred(self)
2193
        Checks for pending exceptions without creating a local reference to the exception object
2194
        Returns:
2195
            boolean: True when there is a pending exception; otherwise return False
2196

    
2197
        """
2198
        return self.thisxptr.exceptionCount() >0
2199

    
2200
     def check_exception(self):
2201
        """
2202
        check_exception(self)
2203
        Check for exception thrown and get message of the exception.
2204

    
2205
        Returns:
2206
            str: Returns the exception message if thrown otherwise return None
2207

    
2208
        """
2209
        cdef const char* c_string = self.thisxptr.checkException()
2210
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
2211
        return ustring
2212

    
2213
     def exception_clear(self):
2214
        """
2215
        exception_clear(self)
2216
        Clear any exception thrown
2217

    
2218
        """
2219
        self.thisxptr.exceptionClear()
2220

    
2221
     def exception_count(self):
2222
        """
2223
        excepton_count(self)
2224
        Get number of errors reported during execution.
2225

    
2226
        Returns:
2227
            int: Count of the exceptions thrown during execution
2228
        """
2229
        return self.thisxptr.exceptionCount()
2230

    
2231
     def get_error_message(self, index):
2232
        """
2233
        get_error_message(self, index)
2234
        A transformation may have a number of errors reported against it. Get the ith error message if there are any errors
2235

    
2236
        Args:
2237
            index (int): The i'th exception
2238

    
2239
        Returns:
2240
            str: The message of the i'th exception. Return None if the i'th exception does not exist.
2241
        """
2242
        cdef const char* c_string = self.thisxptr.getErrorMessage(index)
2243
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
2244
        return ustring
2245

    
2246
     def get_error_code(self, index):
2247
        """
2248
        get_error_code(self, index)
2249
        A transformation may have a number of errors reported against it. Get the i'th error code if there are any errors
2250

    
2251
        Args:
2252
            index (int): The i'th exception
2253

    
2254
        Returns:
2255
            str: The error code associated with the i'th exception. Return None if the i'th exception does not exist.
2256

    
2257
        """
2258
        cdef const char* c_string = self.thisxptr.getErrorCode(index)
2259
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
2260
        return ustring
2261

    
2262

    
2263

    
2264

    
2265
cdef class PyXQueryProcessor:
2266
     """An PyXQueryProcessor object represents factory to compile, load and execute queries. """
2267

    
2268
     cdef saxoncClasses.XQueryProcessor *thisxqptr      # hold a C++ instance which we're wrapping
2269

    
2270
     def __cinit__(self):
2271
        """
2272
        __cinit__(self)
2273
        Constructor for PyXQueryProcessor
2274

    
2275
        """
2276
        self.thisxqptr = NULL
2277

    
2278
     def __dealloc__(self):
2279
        """
2280
        dealloc(self)
2281

    
2282

    
2283
        """
2284
        if self.thisxqptr != NULL:
2285
           del self.thisxqptr
2286

    
2287
     def set_context(self, ** kwds):
2288
        """
2289
        set_context(self, **kwds)
2290
        Set the initial context for the query
2291
   
2292
        Args:
2293
            **kwds : Possible keyword argument file_name (str) or xdm_item (PyXdmItem)
2294

    
2295
        """
2296
        py_error_message = "Error: set_context should only contain one of the following keyword arguments: (file_name|xdm_item)"
2297
        if len(kwds) != 1:
2298
          raise Exception(py_error_message)
2299
        cdef py_value = None
2300
        cdef py_value_string = None
2301
        cdef char * c_source
2302
        cdef PyXdmItem xdm_item = None
2303
        if "file_name" in kwds:
2304
            py_value = kwds["file_name"]
2305
            py_value_string = py_value.encode('UTF-8') if py_value is not None else None
2306
            c_source = py_value_string if py_value is not None else "" 
2307
            self.thisxqptr.setContextItemFromFile(c_source)
2308
        elif "xdm_item" in kwds:
2309
            xdm_item = kwds["xdm_item"]
2310
            xdm_item.derivedptr.incrementRefCount()
2311
            self.thisxqptr.setContextItem(xdm_item.derivedptr)
2312
        else:
2313
          raise Exception(py_error_message)
2314

    
2315
     def set_output_file(self, output_file):
2316
        """
2317
        set_output_file(self, output_file)
2318
        Set the output file where the result is sent
2319

    
2320
        Args:
2321
            output_file (str): Name of the output file
2322
        """
2323
        py_value_string = output_file.encode('UTF-8') if output_file is not None else None
2324
        c_outfile = py_value_string if output_file is not None else ""
2325
        self.thisxqptr.setOutputFile(c_outfile)
2326

    
2327
     def set_parameter(self, name, PyXdmValue value):
2328
        """
2329
        set_parameter(self, name, PyXdmValue value)
2330
        Set the value of a query parameter
2331

    
2332
        Args:
2333
            name (str): the name of the stylesheet parameter, as a string. For namespaced parameter use the JAXP solution i.e. "{uri}name
2334
            value (PyXdmValue): the value of the query parameter, or None to clear a previously set value
2335

    
2336
        """
2337
        cdef const char * c_str = make_c_str(name)
2338
        if c_str is not NULL:
2339
            value.thisvptr.incrementRefCount()
2340
            self.thisxqptr.setParameter(c_str, value.thisvptr)
2341

    
2342
     def remove_parameter(self, name):
2343
        """
2344
        remove_parameter(self, name)
2345
        Remove the parameter given by name from the PyXQueryProcessor. The parameter will not have any affect on the query if it has not yet been executed
2346

    
2347
        Args:
2348
            name (str): The name of the query parameter
2349

    
2350
        Returns:
2351
            bool: True if the removal of the parameter has been successful, False otherwise.
2352

    
2353
        """
2354
        py_value_string = name.encode('UTF-8') if name is not None else None
2355
        c_name = py_value_string if name is not None else ""
2356
        self.thisxqptr.removeParameter(c_name)
2357

    
2358
     def set_property(self, name, str value):
2359
        """
2360
        set_property(self, name, value)
2361
        Set a property specific to the processor in use.
2362
 
2363
        Args:
2364
            name (str): The name of the property
2365
            value (str): The value of the property
2366

    
2367
        Example:
2368
            PyXQueryProcessor: set serialization properties (names start with '!' i.e. name "!method" -> "xml")\r
2369
            'o':outfile name,\r
2370
            'dtd': Possible values 'on' or 'off' to set DTD validation,\r 
2371
            'resources': directory to find Saxon data files,\r 
2372
            's': source as file name,\r
2373
        """
2374

    
2375
        py_name_string = name.encode('UTF-8') if name is not None else None
2376
        c_name = py_name_string if name is not None else ""
2377

    
2378
        py_value_string = value.encode('UTF-8') if value is not None else None
2379
        c_value = py_value_string if value is not None else ""
2380
        self.thisxqptr.setProperty(c_name, c_value)
2381

    
2382
     def clear_parameters(self):
2383
        """
2384
        clear_parameter(self)
2385
        Clear all parameters set on the processor
2386
        """
2387
        self.thisxqptr.clearParameters()
2388

    
2389
     def clear_properties(self):
2390
        """
2391
        clear_parameter(self)
2392
        Clear all properties set on the processor
2393
        """
2394
        self.thisxqptr.clearProperties()
2395

    
2396
     def set_updating(self, updating):
2397
        """
2398
        set_updating(self, updating)
2399
        Say whether the query is allowed to be updating. XQuery update syntax will be rejected during query compilation unless this
2400
        flag is set. XQuery Update is supported only under Saxon-EE/C.
2401

    
2402

    
2403
        Args:
2404
            updating (bool): true if the query is allowed to use the XQuery Update facility (requires Saxon-EE/C). If set to false,
2405
                             the query must not be an updating query. If set to true, it may be either an updating or a non-updating query.
2406

    
2407

    
2408
        """
2409
        self.thisxqptr.setUpdating(updating)
2410

    
2411
     def run_query_to_value(self, ** kwds):
2412
        """
2413
        run_query_to_value(self, **kwds)
2414
        Execute query and output result as an PyXdmValue object 
2415

    
2416
        Args:
2417
            **kwds: Keyword arguments with the possible options input_file_name (str) or input_xdm_item (PyXdmItem). Possible to supply
2418
                    query with the arguments 'query_file' or 'query_text', which are of type str.
2419

    
2420
        Returns:
2421
            PyXdmValue: Output result as an PyXdmValue
2422
        """
2423
        cdef PyXdmNode nval = None
2424
        cdef PyXdmAtomicValue aval = None
2425
        cdef PyXdmValue val = None
2426
        if not len(kwds) == 0:
2427
          
2428
            if "input_file_name" in kwds:
2429
                self.set_context(file_name=kwds["input_file_name"])
2430
            elif "input_xdm_item" in kwds:
2431
                self.set_context(xdm_item=(kwds["xdm_item"]))
2432

    
2433
            if "query_file" in kwds:
2434
                self.set_query_file(kwds["output_file_name"])
2435
            elif "query_text" in kwds:
2436
                self.set_query_content(kwds["query_text"])
2437
        
2438
        cdef saxoncClasses.XdmValue * xdmValue = self.thisxqptr.runQueryToValue()
2439
        if xdmValue is NULL:
2440
            return None        
2441
        cdef type_ = xdmValue.getType()
2442
        if type_== 4:
2443
            aval = PyXdmAtomicValue()
2444
            aval.derivedaptr = aval.derivedptr = aval.thisvptr = <saxoncClasses.XdmAtomicValue *>xdmValue
2445
            return aval        
2446
        elif type_ == 3:
2447
            nval = PyXdmNode()        
2448
            nval.derivednptr = nval.derivedptr = nval.thisvptr = <saxoncClasses.XdmNode*>xdmValue
2449
            return nval
2450
        else:
2451
            val = PyXdmValue()
2452
            val.thisvptr = xdmValue
2453
            return val
2454

    
2455
     def run_query_to_string(self, ** kwds):
2456
        """
2457
        run_query_to_string(self, **kwds)
2458
        Execute query and output result as a string 
2459

    
2460
        Args:
2461
            **kwds: Keyword arguments with the possible options input_file_name (str) or input_xdm_item (PyXdmItem). Possible to supply
2462
                    query with the arguments 'query_file' or 'query_text', which are of type str.
2463

    
2464
        Returns:
2465
            str: Output result as a string
2466
        """
2467
        cdef const char * c_string
2468
        if len(kwds) == 0:
2469
          ustring = make_py_str(self.thisxqptr.runQueryToString())
2470
          return ustring
2471

    
2472
        if "input_file_name" in kwds:
2473
          self.set_context(file_name=kwds["input_file_name"])
2474
        elif "input_xdm_item" in kwds:
2475
          self.set_context(xdm_item=(kwds["xdm_item"]))
2476
        if "query_file" in kwds:
2477
          self.set_query_file(kwds["output_file_name"])
2478
        elif "query_text" in kwds:
2479
          self.set_query_content(kwds["query_text"])
2480
    
2481
        ustring = make_py_str(self.thisxqptr.runQueryToString())
2482
        return ustring
2483
        
2484

    
2485
     def run_query_to_file(self, ** kwds):
2486
        """
2487
        run_query_to_file(self, **kwds)
2488
        Execute query with the result saved to file
2489

    
2490
        Args:
2491
            **kwds: Keyword arguments with the possible options input_file_name (str) or input_xdm_item (PyXdmItem). The Query can be
2492
                    supplied with the arguments 'query_file' or 'query_text', which are of type str. The name of the output file is
2493
                    specified as the argument output_file_name.
2494

    
2495

    
2496
        """
2497
        if len(kwds) == 0:
2498
          self.thisxqptr.runQueryToFile()
2499
        if "input_file_name" in kwds:
2500
          self.set_context(file_name=(kwds["input_file_name"]))
2501
        elif "input_xdm_item" in kwds:
2502
          self.set_context(xdm_item=(kwds["xdm_item"]))
2503
        if "output_file_name" in kwds:
2504
          self.set_output_file(kwds["output_file_name"])
2505
        else:
2506
          raise Exception("Error: output_file_name required in method run_query_to_file")
2507

    
2508
        if "query_file" in kwds:
2509
          self.set_query_file(kwds["output_file_name"])
2510
        elif "query_text" in kwds:
2511
          self.set_query_content(kwds["query_text"])
2512
        self.thisxqptr.runQueryToFile()
2513

    
2514
     def declare_namespace(self, prefix, uri):
2515
        """
2516
        declare_namespace(self, prefix, uri)
2517
        Declare a namespace binding part of the static context for queries compiled using this.
2518
        This binding may be overridden by a binding that appears in the query prolog.
2519
        The namespace binding will form part of the static context of the query, but it will
2520
        not be copied into result trees unless the prefix is actually used in an element or attribute name.
2521

    
2522
        Args:
2523
            prefix (str): The namespace prefix. If the value is a zero-length string, this method sets the default namespace for elements and types.
2524
            uri (uri) : The namespace URI. It is possible to specify a zero-length string to "undeclare" a namespace; in this case the prefix will not be available for use,
2525
            except in the case where the prefix is also a zero length string, in which case the absence of a prefix implies that the name is in no namespace.
2526

    
2527
        """
2528
        c_prefix = make_c_str(prefix)
2529
        c_uri = make_c_str(uri)
2530
        self.thisxqptr.declareNamespace(c_prefix, c_uri)
2531

    
2532
     def set_query_file(self, file_name):
2533
        """
2534
        set_query_file(self, file_name)
2535
        Set the query to be executed as a file
2536

    
2537
        Args:
2538
            file_name (str): The file name for the query
2539

    
2540

    
2541
        """
2542
        c_filename = make_c_str(file_name)
2543
        self.thisxqptr.setQueryFile(c_filename)
2544

    
2545
     def set_query_content(self, content):
2546
        """
2547
        set_query_content(self)
2548
        Set the query to be executed as a string
2549

    
2550
        Args:
2551
            content (str): The query content suplied as a string
2552

    
2553
        """
2554
        if content is not None:
2555
            c_content = make_c_str(content)
2556
            self.thisxqptr.setQueryContent(c_content)
2557

    
2558
     def set_query_base_uri(self, base_uri):
2559
        """
2560
        set_query_base_uri(self, base_uri)
2561
        Set the static base query for the query     
2562

    
2563
        Args:
2564
            base_uri (str): The static base URI; or None to indicate that no base URI is available
2565
        """
2566
        py_content_string = base_uri.encode('UTF-8') if base_uri is not None else None
2567
        c_content = py_content_string if base_uri is not None else ""
2568
        self.thisxqptr.setQueryBaseURI(c_content)
2569

    
2570
     def set_cwd(self, cwd):
2571
        """
2572
        set_cwd(self, cwd)
2573
        Set the current working directory.
2574

    
2575
        Args:
2576
            cwd (str): current working directory
2577
        """
2578
        py_cwd_string = cwd.encode('UTF-8') if cwd is not None else None
2579
        c_cwd = py_cwd_string if cwd is not None else ""
2580
        self.thisxqptr.setcwd(c_cwd)
2581

    
2582
     def check_exception(self):
2583
        """
2584
        check_exception(self)
2585
        Check for exception thrown and get message of the exception.
2586
  
2587
        Returns:
2588
            str: Returns the exception message if thrown otherwise return None
2589

    
2590
        """
2591
        return self.thisxqptr.checkException()
2592

    
2593
     def exception_occurred(self):
2594
        """
2595
        exception_occurred(self)
2596
        Checks for pending exceptions without creating a local reference to the exception object
2597

    
2598
        Returns:
2599
            boolean: True when there is a pending exception; otherwise return False
2600

    
2601
        """
2602
        return self.thisxqptr.exceptionCount() >0
2603

    
2604
     def exception_clear(self):
2605
        """
2606
        exception_clear(self)
2607
        Clear any exception thrown
2608

    
2609
        """
2610
        self.thisxqptr.exceptionClear()
2611

    
2612
     def exception_count(self):
2613
        """
2614
        excepton_count(self)
2615
        Get number of errors reported during execution.
2616

    
2617
        Returns:
2618
            int: Count of the exceptions thrown during execution
2619
        """
2620
        return self.thisxqptr.exceptionCount()
2621

    
2622
     def get_error_message(self, index):
2623
        """
2624
        get_error_message(self, index)
2625
        A transformation may have a number of errors reported against it. Get the ith error message if there are any errors
2626

    
2627
        Args:
2628
            index (int): The i'th exception
2629
        
2630
        Returns:
2631
            str: The message of the i'th exception. Return None if the i'th exception does not exist.
2632
        """
2633
        return make_py_str(self.thisxqptr.getErrorMessage(index))
2634

    
2635
     def get_error_code(self, index):
2636
        """
2637
        get_error_code(self, index)
2638
        A transformation may have a number of errors reported against it. Get the i'th error code if there are any errors
2639

    
2640
        Args:
2641
            index (int): The i'th exception
2642
        
2643
        Returns:
2644
            str: The error code associated with the i'th exception. Return None if the i'th exception does not exist.
2645

    
2646
        """
2647
        return make_py_str(self.thisxqptr.getErrorCode(index))
2648

    
2649
cdef class PyXPathProcessor:
2650
     """An XPathProcessor represents factory to compile, load and execute the XPath query. """
2651
     cdef saxoncClasses.XPathProcessor *thisxpptr      # hold a C++ instance which we're wrapping
2652

    
2653
     def __cinit__(self):
2654
        """
2655
        cinit(self)
2656
        Constructor for PyXPathProcessor 
2657

    
2658
        """
2659
        self.thisxpptr = NULL
2660
     def __dealloc__(self):
2661
        """
2662
        dealloc(self)
2663

    
2664

    
2665
        """
2666
        if self.thisxpptr != NULL:
2667
           del self.thisxpptr
2668

    
2669

    
2670
     def evaluate(self, xpath_str):
2671
        """
2672
        evaluate(self, xpath_str)
2673

    
2674
        Args:
2675
            xpath_str (str): The XPath query suplied as a string
2676

    
2677
        Returns:
2678
            PyXdmValue: 
2679

    
2680
        """
2681
        py_string = xpath_str.encode('UTF-8') if xpath_str is not None else None
2682
        c_xpath = py_string if xpath_str is not None else ""
2683
        cdef PyXdmNode nval = None
2684
        cdef PyXdmAtomicValue aval = None
2685
        cdef PyXdmValue val = None
2686
        cdef type_ = 0
2687
        cdef saxoncClasses.XdmValue * xdmValue = self.thisxpptr.evaluate(c_xpath)
2688
        if xdmValue == NULL:
2689
            return None
2690
        else:
2691
            type_ = xdmValue.getType()        
2692
            if type_ == 4:
2693
                aval = PyXdmAtomicValue()
2694
                aval.derivedaptr = aval.derivedptr = aval.thisvptr = <saxoncClasses.XdmAtomicValue *>xdmValue
2695
                return aval        
2696
            elif type_ == 3:
2697
                nval = PyXdmNode()
2698
                nval.derivednptr = nval.derivedptr = nval.thisvptr = <saxoncClasses.XdmNode*>xdmValue
2699
                return nval
2700
            else:
2701
                val = PyXdmValue()
2702
                val.thisvptr = xdmValue
2703
                return val
2704

    
2705
     def evaluate_single(self, xpath_str):
2706
        """
2707
        evaluate_single(self, xpath_str)
2708

    
2709
        Args:
2710
            xpath_str (str): The XPath query supplied as a string
2711

    
2712
        Returns:
2713
            PyXdmItem: A single Xdm Item is returned 
2714

    
2715
        """
2716
        cdef PyXdmNode val = None
2717
        cdef PyXdmAtomicValue aval = None
2718
        py_string = xpath_str.encode('UTF-8') if xpath_str is not None else None
2719
        c_xpath = py_string if xpath_str is not None else ""
2720

    
2721
        cdef saxoncClasses.XdmItem * xdmItem = self.thisxpptr.evaluateSingle(c_xpath)
2722
        if xdmItem == NULL:
2723
            return None
2724
        cdef type_ = xdmItem.getType()        
2725
        if type_ == 4:
2726
            aval = PyXdmAtomicValue()
2727
            aval.derivedaptr = aval.derivedptr = aval.thisvptr = <saxoncClasses.XdmAtomicValue *>xdmItem
2728
            return aval        
2729
        elif type_ == 3:
2730
            val = PyXdmNode()
2731
            val.derivednptr = val.derivedptr = val.thisvptr = <saxoncClasses.XdmNode*>xdmItem
2732
            return val
2733
        else:
2734
            return None
2735
        
2736

    
2737
     def set_context(self, **kwds):
2738
        """
2739
        set_context(self, **kwds)
2740
        Set the context for the XPath query
2741
   
2742
        Args:
2743
            **kwds : Possible keyword argument file_name (str) or xdm_item (PyXdmItem)
2744

    
2745
        """
2746
        py_error_message = "Error: set_context should only contain one of the following keyword arguments: (file_name|xdm_item)"
2747
        if len(kwds) != 1:
2748
          raise Exception(py_error_message)
2749
        cdef py_value = None
2750
        cdef py_value_string = None
2751
        cdef char * c_source
2752
        cdef PyXdmItem xdm_item = None
2753
        if "file_name" in kwds:
2754
            py_value = kwds["file_name"]
2755
            py_value_string = py_value.encode('UTF-8') if py_value is not None else None
2756
            c_source = py_value_string if py_value is not None else "" 
2757
            self.thisxpptr.setContextFile(c_source)
2758
        elif "xdm_item" in kwds:
2759
            xdm_item = kwds["xdm_item"]
2760
            xdm_item.derivedptr.incrementRefCount()
2761
            self.thisxpptr.setContextItem(xdm_item.derivedptr)
2762
        else:
2763
          raise Exception(py_error_message)
2764

    
2765
     def set_cwd(self, cwd):
2766
        """
2767
        set_cwd(self, cwd)
2768
        Set the current working directory.
2769

    
2770
        Args:
2771
            cwd (str): current working directory
2772
        """
2773
        py_cwd_string = cwd.encode('UTF-8') if cwd is not None else None
2774
        cdef char * c_cwd = py_cwd_string if cwd is not None else "" 
2775
        self.thisxpptr.setcwd(c_cwd)
2776

    
2777
     def effective_boolean_value(self, xpath_str):
2778
        """
2779
        effective_boolean_value(self, xpath_str)
2780
        Evaluate the XPath expression, returning the effective boolean value of the result.
2781
    
2782
        Args:
2783
            xpath_str (str): Supplied as a string
2784

    
2785
        Returns:
2786
            boolean: The result is a boolean value.
2787
        """
2788

    
2789
        py_value_string = xpath_str.encode('UTF-8') if xpath_str is not None else None
2790
        c_xpath = py_value_string if xpath_str is not None else "" 
2791

    
2792
        return self.thisxpptr.effectiveBooleanValue(c_xpath)
2793

    
2794
     def set_parameter(self, name, PyXdmValue value):
2795
        """
2796
        set_parameter(self, name, PyXdmValue value)
2797
        Set the value of a XPath parameter
2798

    
2799
        Args:
2800
            name (str): the name of the XPath parameter, as a string. For namespaced parameter use the JAXP solution i.e. "{uri}name
2801
            value (PyXdmValue): the value of the query parameter, or None to clear a previously set value
2802

    
2803
        """
2804
        cdef const char * c_str = make_c_str(name)
2805
        if c_str is not NULL:
2806
            self.thisxpptr.setParameter(c_str, value.thisvptr)
2807

    
2808
     def remove_parameter(self, name):
2809
        """
2810
        remove_parameter(self, name)
2811
        Remove the parameter given by name from the PyXPathProcessor. The parameter will not have any affect on the XPath if it has not yet been executed
2812

    
2813
        Args:
2814
            name (str): The name of the XPath parameter
2815

    
2816
        Returns:
2817
            bool: True if the removal of the parameter has been successful, False otherwise.
2818

    
2819
        """
2820
        self.thisxpptr.removeParameter(name)
2821
     def set_property(self, name, value):
2822
        """
2823
        set_property(self, name, value)
2824
        Set a property specific to the processor in use.
2825
 
2826
        Args:
2827
            name (str): The name of the property
2828
            value (str): The value of the property
2829

    
2830
        Example:
2831
            PyXPathProcessor: set serialization properties (names start with '!' i.e. name "!method" -> "xml")\r
2832
            'resources': directory to find Saxon data files,\r 
2833
            's': source as file name,\r
2834
            'extc': REgister native library to be used with extension functions
2835
        """
2836

    
2837
        py_name_string = name.encode('UTF-8') if name is not None else None
2838
        c_name = py_name_string if name is not None else ""
2839

    
2840
        py_value_string = value.encode('UTF-8') if value is not None else None
2841
        c_value = py_value_string if value is not None else ""
2842
        self.thisxpptr.setProperty(c_name, c_value)
2843
     def declare_namespace(self, prefix, uri):
2844
        """
2845
        declare_namespace(self, prefix, uri)
2846
        Declare a namespace binding as part of the static context for XPath expressions compiled using this compiler
2847
        Args:
2848
            prefix (str): The namespace prefix. If the value is a zero-length string, this method sets the default namespace
2849
                          for elements and types.
2850
            uri (uri) : The namespace URI. It is possible to specify a zero-length string to "undeclare" a namespace;
2851
                        in this case the prefix will not be available for use, except in the case where the prefix is also a
2852
                        zero length string, in which case the absence of a prefix implies that the name is in no namespace.
2853

    
2854
        """
2855
        py_prefix_string = prefix.encode('UTF-8') if prefix is not None else None
2856
        c_prefix = py_prefix_string if prefix is not None else ""
2857
        py_uri_string = uri.encode('UTF-8') if uri is not None else None
2858
        c_uri = py_uri_string if uri is not None else ""
2859
        self.thisxpptr.declareNamespace(c_prefix, c_uri)
2860

    
2861
     def set_backwards_compatible(self, option):
2862
        cdef bool c_option
2863
        c_option = option
2864
        self.thisxpptr.setBackwardsCompatible(c_option)
2865

    
2866
     def set_caching(self, is_caching):
2867
         cdef bool c_is_caching
2868
         c_is_caching = is_caching
2869
         self.thisxpptr.setCaching(c_is_caching)
2870

    
2871
     def import_schema_namespace(self, uri):
2872
         py_uri_string = uri.encode('UTF-8') if uri is not None else None
2873
         c_name = py_uri_string if uri is not None else ""
2874
         self.thisxpptr.importSchemaNamespace(c_name)
2875

    
2876
     def clear_parameters(self):
2877
        """
2878
        clear_parameter(self)
2879
        Clear all parameters set on the processor
2880
        """
2881
        self.thisxpptr.clearParameters()
2882
     def clear_properties(self):
2883
        """
2884
        clear_parameter(self)
2885
        Clear all properties set on the processor
2886
        """
2887
        self.thisxpptr.clearProperties()
2888
     def check_exception(self):
2889
        """
2890
        check_exception(self)
2891
        Check for exception thrown and get message of the exception.
2892
  
2893
        Returns:
2894
            str: Returns the exception message if thrown otherwise return None
2895

    
2896
        """
2897
        return self.thisxpptr.checkException()
2898
     def exception_occurred(self):
2899
        """
2900
        exception_occurred(self)
2901
        Check if an exception has occurred internally within Saxon/C
2902

    
2903
        Returns:
2904
            boolean: True or False if an exception has been reported internally in Saxon/C
2905
        """
2906

    
2907
        return self.thisxpptr.exceptionCount() >0
2908

    
2909
     def exception_clear(self):
2910
        """
2911
        exception_clear(self)
2912
        Clear any exception thrown
2913

    
2914
        """
2915
        self.thisxpptr.exceptionClear()
2916
     def exception_count(self):
2917
        """
2918
        excepton_count(self)
2919
        Get number of errors reported during execution.
2920

    
2921
        Returns:
2922
            int: Count of the exceptions thrown during execution
2923
        """
2924
        return self.thisxpptr.exceptionCount()
2925
     def get_error_message(self, index):
2926
        """
2927
        get_error_message(self, index)
2928
        A transformation may have a number of errors reported against it. Get the ith error message if there are any errors
2929

    
2930
        Args:
2931
            index (int): The i'th exception
2932
        
2933
        Returns:
2934
            str: The message of the i'th exception. Return None if the i'th exception does not exist.
2935
        """
2936
        return make_py_str(self.thisxpptr.getErrorMessage(index))
2937
     def get_error_code(self, index):
2938
        """
2939
        get_error_code(self, index)
2940
        A transformation may have a number of errors reported against it. Get the i'th error code if there are any errors
2941

    
2942
        Args:
2943
            index (int): The i'th exception
2944
        
2945
        Returns:
2946
            str: The error code associated with the i'th exception. Return None if the i'th exception does not exist.
2947

    
2948
        """
2949
        return make_py_str(self.thisxpptr.getErrorCode(index))
2950

    
2951

    
2952
cdef class PySchemaValidator:
2953
     """An PySchemaValidator represents factory for validating instance documents against a schema."""
2954
     
2955
     cdef saxoncClasses.SchemaValidator *thissvptr      # hold a C++ instance which we're wrapping
2956

    
2957
     def __cinit__(self):
2958
        self.thissvptr = NULL
2959
     def __dealloc__(self):
2960
        if self.thissvptr != NULL:
2961
           del self.thissvptr
2962

    
2963
     def set_cwd(self, cwd):
2964
        """
2965
        set_cwd(self, cwd)
2966
        Set the current working directory.
2967

    
2968
        Args:
2969
            cwd (str): current working directory
2970
        """
2971
        py_cwd_string = cwd.encode('UTF-8') if cwd is not None else None
2972
        cdef char * c_cwd = py_cwd_string if cwd is not None else "" 
2973
        self.thissvptr.setcwd(c_cwd)
2974

    
2975
     def register_schema(self, **kwds):
2976
        """
2977
        Register schema given as file name or schema text. (xsd_text|xsd_file)
2978

    
2979
        Args:
2980
            **kwds: Keyword argument options only one of 'xsd_text' or 'xsd_file'
2981

    
2982
        """
2983
        py_error_message = "Error: register_schema should only contain one of the following keyword arguments: (xsd_text|xsd_file)"
2984
        if len(kwds) != 1:
2985
          raise Exception(py_error_message)
2986
        cdef py_value = None
2987
        cdef py_value_string = None
2988
        cdef char * c_source
2989
        
2990
        if "xsd_text" in kwds:
2991
            py_value = kwds["xsd_text"]
2992
            py_value_string = py_value.encode('UTF-8') if py_value is not None else None
2993
            c_source = py_value_string if py_value is not None else "" 
2994
            self.thissvptr.registerSchemaFromString(c_source)
2995
        elif "xsd_file" in kwds:
2996
            py_value = kwds["xsd_file"]
2997
            py_value_string = py_value.encode('UTF-8') if py_value is not None else None
2998
            c_source = py_value_string if py_value is not None else "" 
2999
            self.thissvptr.registerSchemaFromFile(c_source)
3000
        else:
3001
          raise Exception(py_error_message)
3002

    
3003
     def export_schema(self, file_name):
3004
        """
3005
        export_schema(self, file_name)
3006
        Export a precompiled Schema Component Model containing all the components (except built-in components) that have been loaded
3007

    
3008
        Args:
3009
            file_name (str):The file name that will be used for thje saved SCM
3010

    
3011
        """
3012
        py_value_string = file_name.encode('UTF-8') if file_name is not None else None
3013
        c_source = py_value_string
3014
        if file_name is not None:
3015
            self.thissvptr.exportSchema(c_source)
3016
        else:
3017
            raise Warning("Unable to export the Schema. file_name has the value None")
3018

    
3019
        
3020
     def set_output_file(self, output_file):
3021
        """
3022
        set_output_file(self, output_file)
3023
        Set the name of the output file that will be used by the validator.
3024

    
3025
        Args:
3026
            output_file (str):The output file name for use by the validator
3027
    
3028
        """
3029
        py_value_string = output_file.encode('UTF-8') if output_file is not None else None
3030
        c_source = py_value_string 
3031
        if output_file is not None:
3032
            self.thissvptr.setOutputFile(c_source)
3033
        else:
3034
            raise Warning("Unable to set output_file. output_file has the value None")
3035

    
3036
     def validate(self, **kwds):
3037
        """
3038
        validate(self, **kwds)
3039
        Validate an instance document by a registered schema.
3040
        
3041
        Args:
3042
            **kwds: The possible keyword arguments must be one of the follow (file_name|xml_text|xdm_node).
3043
                    The source file to be validated. Allow None when source document is supplied using the set_source method
3044
        """
3045
        py_error_message = "Error: validate should only contain one of the following keyword arguments: (file_name|xdm_node|xml_text)"
3046
        if len(kwds) > 1:
3047
          raise Exception(py_error_message)
3048
        cdef py_value = None
3049
        cdef py_value_string = None
3050
        cdef char * c_source
3051
        cdef PyXdmNode xdm_node = None
3052
        if "file_name" in kwds:
3053
            py_value = kwds["file_name"]
3054
            py_value_string = py_value.encode('UTF-8') if py_value is not None else None
3055
            c_source = py_value_string if py_value is not None else ""
3056
            self.thissvptr.validate(c_source)
3057
        elif "xdm_node" in kwds:
3058
            xdm_node = kwds["xdm_node"]
3059
            if isinstance(xdm_node, PyXdmNode):
3060
               self.thissvptr.setSourceNode(xdm_node.derivednptr)
3061
               self.thissvptr.validate(NULL)
3062
        else:
3063
            self.thissvptr.validate(NULL)
3064

    
3065

    
3066
     def validate_to_node(self, **kwds):
3067
        """
3068
        validate_to_node(self, **kwds)
3069
        Validate an instance document by a registered schema.
3070
        
3071

    
3072
        Args:
3073
            **kwds: The possible keyword arguments must be one of the follow (file_name|xml_text|xdm_node).
3074
                    The source file to be validated. Allow None when source document is supplied using the set_source method
3075

    
3076
        Returns:
3077
            PyXdmNode: The validated document returned to the calling program as an PyXdmNode    
3078
        """
3079
        py_error_message = "Error: validate should only contain one of the following keyword arguments: (file_name|xdm_node|xml_text)"
3080
        if len(kwds) > 1:
3081
          raise Exception(py_error_message)
3082
        cdef py_value = None
3083
        cdef py_value_string = None
3084
        cdef char * c_source
3085
        cdef PyXdmNode xdm_node = None
3086
        cdef PyXdmNode val = None
3087
        cdef saxoncClasses.XdmNode * xdmNode = NULL
3088

    
3089
        if "file_name" in kwds:
3090
            py_value = kwds["file_name"]
3091
            py_value_string = py_value.encode('UTF-8') if py_value is not None else None
3092
            c_source = py_value_string if py_value is not None else ""
3093
            if isfile(py_value_string) == False:
3094
                raise Exception("Source file with name "+py_value_string+" does not exist")
3095
            xdmNode = self.thissvptr.validateToNode(c_source)
3096
        elif "xdm_node" in kwds:
3097
            xdm_node = kwds["xdm_node"]
3098
            if isinstance(xdm_node, PyXdmNode):
3099
                self.thissvptr.setSourceNode(xdm_node.derivednptr)
3100
                xdmNode = self.thissvptr.validateToNode(NULL)
3101
        else:
3102
            xdmNode = self.thissvptr.validateToNode(NULL)
3103
            
3104
        if xdmNode == NULL:
3105
            return None
3106
        else:
3107
            val = PyXdmNode()
3108
            val.derivednptr = val.derivedptr = val.thisvptr =  xdmNode
3109
            return val
3110

    
3111
     def set_source_node(self, PyXdmNode source):
3112
        """
3113
        set_source_node(self, source)
3114
        Set the source as an PyXdmNode object that will be validated
3115

    
3116
        Args:
3117
            source (PyXdmNode) :
3118
        """
3119
        self.thissvptr.setSourceNode(source.derivednptr)
3120

    
3121
     @property
3122
     def validation_report(self):
3123
        """
3124
        validation_report
3125
        The validation report Property
3126

    
3127
        :PyXdmNode: The Validation report result from the Schema validator
3128

    
3129
        """
3130
        cdef PyXdmNode val = None
3131
        cdef saxoncClasses.XdmNode * xdmNode = NULL             
3132
        xdmNode = self.thissvptr.getValidationReport()
3133
        if xdmNode == NULL:
3134
            return None
3135
        else:
3136
            val = PyXdmNode()
3137
            val.derivednptr = val.derivedptr = val.thisvptr = xdmNode
3138
            return val
3139

    
3140
     def set_parameter(self, name, PyXdmValue value):
3141
        """
3142
        set_parameter(self, name, PyXdmValue value)
3143
        Set the value of the parameter for the Schema validator
3144

    
3145
        Args:
3146
            name (str): the name of the schema parameter, as a string. For namespaced parameter use the JAXP solution i.e. "{uri}name
3147
            value (PyXdmValue): the value of the parameter, or None to clear a previously set value
3148

    
3149
        """
3150
        cdef const char * c_str = make_c_str(name)
3151
        if c_str is not NULL:
3152
            value.thisvptr.incrementRefCount()
3153
            self.thissvptr.setParameter(c_str, value.thisvptr)
3154

    
3155
     def remove_parameter(self, name):
3156
        """
3157
        remove_parameter(self, name)
3158
        Remove the parameter given by name from the PySchemaValidator. The parameter will not have any affect on the SchemaValidator if it has not yet been executed
3159

    
3160
        Args:
3161
            name (str): The name of the schema parameter
3162

    
3163
        Returns:
3164
            bool: True if the removal of the parameter has been successful, False otherwise.
3165

    
3166
        """
3167
        cdef const char * c_str = make_c_str(name)
3168
        if c_str is not NULL:
3169
            self.thissvptr.removeParameter(c_str)
3170
     def set_property(self, name, value):
3171
        """
3172
        set_property(self, name, value)
3173
        Set a property specific to the processor in use.
3174
 
3175
        Args:
3176
            name (str): The name of the property
3177
            value (str): The value of the property
3178

    
3179
        Example:
3180
            PySchemaValidator: set serialization properties (names start with '!' i.e. name "!method" -> "xml")\r
3181
            'o':outfile name,\r
3182
            'dtd': Possible values 'on' or 'off' to set DTD validation,\r 
3183
            'resources': directory to find Saxon data files,\r 
3184
            's': source as file name,\r
3185
            'string': Set the source as xml string for validation. Parsing will take place in the validate method\r
3186
            'report-node': Boolean flag for validation reporting feature. Error validation failures are represented in an XML
3187
                           document and returned as an PyXdmNode object\r
3188
            'report-file': Specifcy value as a file name string. This will switch on the validation reporting feature, which will be
3189
                           saved to the file in an XML format\r
3190
            'verbose': boolean value which sets the verbose mode to the output in the terminal. Default is 'on'
3191
            'element-type': Set the name of the required type of the top-lelvel element of the doucment to be validated.
3192
                            The string should be in the Clark notation {uri}local\r
3193
            'lax': Boolean to set the validation mode to strict (False) or lax ('True')
3194
        """
3195

    
3196
        cdef const char * c_name = make_c_str(name)
3197
        cdef const char * c_value = make_c_str(value)
3198
        if c_name is not NULL:
3199
            if c_value is not NULL:
3200
                self.thissvptr.setProperty(c_name, c_value)
3201

    
3202
     def clear_parameters(self):
3203
        """
3204
        clear_parameter(self)
3205
        Clear all parameters set on the processor
3206
        """
3207
        self.thissvptr.clearParameters()
3208
     def clear_properties(self):
3209
        """
3210
        clear_parameter(self)
3211
        Clear all properties set on the processor
3212
        """
3213
        self.thissvptr.clearProperties()
3214
     def exception_occurred(self):
3215
        """
3216
        exception_occurred(self)
3217
        Check if an exception has occurred internally within Saxon/C
3218

    
3219
        Returns:
3220
            boolean: True or False if an exception has been reported internally in Saxon/C
3221
        """
3222
        return self.thissvptr.exceptionCount()>0
3223

    
3224
     def exception_clear(self):
3225
        """
3226
        exception_clear(self)
3227
        Clear any exception thrown
3228

    
3229
        """
3230
        self.thissvptr.exceptionClear()
3231
     def exception_count(self):
3232
        """
3233
        excepton_count(self)
3234
        Get number of errors reported during execution of the schema.
3235

    
3236
        Returns:
3237
            int: Count of the exceptions thrown during execution
3238
        """
3239
        return self.thissvptr.exceptionCount()
3240
     def get_error_message(self, index):
3241
        """
3242
        get_error_message(self, index)
3243
        A transformation may have a number of errors reported against it. Get the ith error message if there are any errors
3244

    
3245
        Args:
3246
            index (int): The i'th exception
3247
        
3248
        Returns:
3249
            str: The message of the i'th exception. Return None if the i'th exception does not exist.
3250
        """
3251
        return make_py_str(self.thissvptr.getErrorMessage(index))
3252

    
3253
     def get_error_code(self, index):
3254
        """
3255
        get_error_code(self, index)
3256
        A transformation may have a number of errors reported against it. Get the i'th error code if there are any errors.
3257

    
3258
        Args:
3259
            index (int): The i'th exception
3260
        
3261
        Returns:
3262
            str: The error code associated with the i'th exception. Return None if the i'th exception does not exist.
3263

    
3264
        """
3265
        return make_py_str(self.thissvptr.getErrorCode(index))
3266

    
3267
     def set_lax(self, lax):
3268
        """
3269
        set_lax(self, lax)
3270
        The validation mode may be either strict or lax. \r
3271
        The default is strict; this method may be called to indicate that lax validation is required. With strict validation,
3272
        validation fails if no element declaration can be located for the outermost element. With lax validation,
3273
        the absence of an element declaration results in the content being considered valid.
3274
        
3275
        Args:
3276
            lax (boolean): lax True if validation is to be lax, False if it is to be strict
3277

    
3278
        """
3279
        self.thissvptr.setLax(lax)
3280

    
3281
cdef class PyXdmValue:
3282
     """Value in the XDM data model. A value is a sequence of zero or more items, each item being either an atomic value or a node. """    
3283
     cdef saxoncClasses.XdmValue *thisvptr      # hold a C++ instance which we're wrapping
3284

    
3285
     def __cinit__(self):
3286
        """
3287
        cinit(self)
3288
        Constructor for PyXdmValue
3289

    
3290
        """
3291
        if type(self) is PyXdmValue:
3292
            self.thisvptr = new saxoncClasses.XdmValue() 
3293
     def __dealloc__(self):
3294
        if type(self) is PyXdmValue and self.thisvptr != NULL:    
3295
            if self.thisvptr.getRefCount() < 1:
3296
                del self.thisvptr            
3297
            else:
3298
                self.thisvptr.decrementRefCount()
3299

    
3300

    
3301
     def add_xdm_item(self, PyXdmItem value):
3302
        """
3303
        add_xdm_tem(self, PyXdmItem value)
3304
        Add PyXdmItem to the Xdm sequence
3305

    
3306
        Args:
3307
            value (PyXdmItem): The PyXdmItem object
3308
        """
3309
        self.thisvptr.addXdmItem(value.derivedptr)
3310

    
3311
     @property
3312
     def head(self):
3313
        """
3314
        head(self)
3315
        Property to get the first item in the sequence
3316

    
3317
        Returns:
3318
            PyXdmItem: The PyXdmItem or None if the sequence is empty
3319

    
3320
        """
3321
        cdef PyXdmItem val = PyXdmItem()
3322
        val.derivedptr = val.thisvptr = self.thisvptr.getHead()
3323
        if val.derivedptr == NULL :
3324
            return None
3325
        else:
3326
            val.derivedptr.incrementRefCount()
3327
            return val
3328

    
3329
     def item_at(self, index):
3330
        """
3331
        item_at(self, index)
3332
        Get the n'th item in the value, counting from zero.
3333
        
3334
        Args:
3335
            index (int): the index of the item required. Counting from zero
3336
        Returns:
3337
            PyXdmItem: Get the item indicated at the index. This could be PyXdmNode or PyXdmAtomicValue object. If the item does not exist return None.
3338
        
3339

    
3340
        """
3341
        cdef PyXdmValue val = None
3342
        cdef PyXdmAtomicValue aval = None
3343
        cdef PyXdmNode nval = None
3344
        cdef PyXdmItem val = None
3345
        cdef type_ = None
3346
        cdef saxoncClasses.XdmItem * xdmItem = NULL
3347
        xdmItem = self.thisvptr.itemAt(index)
3348
        if xdmItem == NULL:
3349
            return None
3350
        else :
3351
            type_ = xdmItem.getType()
3352

    
3353
            xdmItem.incrementRefCount()
3354
            if type_== 4:
3355
                aval = PyXdmAtomicValue()
3356
                aval.derivedaptr = aval.derivedptr = aval.thisvptr = <saxoncClasses.XdmAtomicValue *>xdmItem
3357
                return aval
3358
            elif type_ == 3:
3359
                nval = PyXdmNode()
3360
                nval.derivednptr = nval.derivedptr = nval.thisvptr = <saxoncClasses.XdmNode*>xdmItem
3361
                return nval
3362
            else:
3363
                val = PyXdmItem()
3364
                val.thisvptr = xdmItem
3365
                return val
3366

    
3367
     @property
3368
     def size(self):
3369
        """
3370
        size(self)
3371
        Property - Get the number of items in the sequence
3372
        
3373
        Returns:
3374
            int: The count of items in the sequence
3375
        """
3376
        return self.thisvptr.size()
3377

    
3378
     def __repr__(self):
3379
        """
3380
        __repr__(self)
3381
        The string representation of PyXdmItem
3382

    
3383
        """
3384
        cdef const char* c_string = self.thisvptr.toString()
3385
        if c_string == NULL:
3386
            raise Warning('Empty string returned')
3387
        else:
3388
            ustring = c_string.decode('UTF-8') if c_string is not NULL else None
3389
            return ustring
3390

    
3391
     def __str__(self):
3392
        """
3393
        __str__(self)
3394
        The string representation of PyXdmItem
3395

    
3396
        """
3397
        cdef const char* c_string = self.thisvptr.toString()
3398
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
3399
        return ustring 
3400

    
3401
cdef class PyXdmItem(PyXdmValue):
3402
     cdef saxoncClasses.XdmItem *derivedptr      # hold a C++ instance which we're wrapping
3403

    
3404
     def __cinit__(self):
3405
        if type(self) is PyXdmItem:
3406
            self.derivedptr = self.thisvptr = new saxoncClasses.XdmItem()
3407
     def __dealloc__(self):
3408
        if type(self) is PyXdmItem and self.derivedptr != NULL:
3409
            if self.derivedptr.getRefCount() < 1:
3410
                del self.derivedptr            
3411
            else:
3412
                self.derivedptr.decrementRefCount()
3413

    
3414
        '''if type(self) is PyXdmItem:
3415
            del self.derivedptr'''
3416

    
3417
     @property
3418
     def string_value(self):
3419
        """
3420
        string_value(self)
3421
        Property to get the the strign value of the XdmItem 
3422
        """
3423
        cdef const char* c_string = self.derivedptr.getStringValue()
3424
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
3425
        return ustring
3426

    
3427

    
3428
     def __repr__(self):
3429
        return make_py_str(self.derivedptr.getStringValue())
3430

    
3431
     def __str__(self):
3432
        return make_py_str(self.derivedptr.getStringValue())
3433

    
3434
     @property
3435
     def is_atomic(self):
3436
        """
3437
        is_atomic(self)
3438
        Property to check if the current PyXdmItem is an atomic value
3439
    
3440
        Returns:
3441
            bool: Check of is atomic value 
3442
        """
3443
        return self.derivedptr.isAtomic()
3444

    
3445
     def get_node_value(self):
3446
        """
3447
        get_node_value(self)
3448
        Get the subclass PyXdmNode for this PyXdmItem object current object if it is a node value
3449
    
3450
        Returns:
3451
            PyXdmNode: Subclass this object to PyXdmNode or error 
3452
        """
3453
        cdef PyXdmNode val = None
3454
        if self.is_atomic:
3455
          raise Exception("The PyXdmItem is an PyXdmAtomicValue therefore cannot be sub-classed to an PyXdmNode")
3456
        val = PyXdmNode()
3457
        val.derivednptr = val.derivedptr = <saxoncClasses.XdmNode*> self.derivedptr
3458
        '''val.derivednptr.incrementRefCount()'''
3459
        return val
3460

    
3461
     @property
3462
     def head(self):
3463
        """
3464
        head(self)
3465
        Property to get the first item in the sequence. This would be the PyXdmItem itself as there is only one item in the sequence
3466

    
3467
        Returns:
3468
            PyXdmItem: The PyXdmItem or None if the sequence is empty
3469

    
3470
        """
3471
        return self
3472

    
3473
     def get_atomic_value(self):
3474
        """
3475
        get_atomic_value(self)
3476
        Get the subclass PyXdmAtomicValue for this PyXdmItem object current object if it is an atomic value
3477
    
3478
        Returns:
3479
            PyXdmAtomicValue: Subclass this object to PyXdmAtomicValue or error 
3480
        """
3481
        if self.is_atomic == False:
3482
          raise Exception("The PyXdmItem is not an PyXdmAtomicValue")
3483
        val = PyXdmAtomicValue()
3484
        val.derivedaptr = val.derivedptr = <saxoncClasses.XdmAtomicValue*>self.derivedptr
3485
        val.derivedaptr.incrementRefCount()
3486
        return val
3487

    
3488
cdef class PyXdmNode(PyXdmItem):
3489
     cdef saxoncClasses.XdmNode *derivednptr      # hold a C++ instance which we're wrapping
3490

    
3491
     def __cinit__(self):
3492
        self.derivednptr = self.derivedptr = self.thisvptr = NULL
3493
    
3494
     def __dealloc__(self):
3495
        if type(self) is PyXdmNode and self.derivednptr != NULL:
3496
                 if self.derivednptr.getRefCount() < 1:
3497
                     del self.derivednptr
3498
                 else:
3499
                     self.derivednptr.decrementRefCount()
3500

    
3501
     @property
3502
     def head(self):
3503
        """
3504
        head(self)
3505
        Property to get the first item in the sequence. This would be the PyXdmNode itself as there is only one item in the sequence
3506

    
3507
        Returns:
3508
            PyXdmItem: The PyXdmItem or None if the sequence is empty
3509

    
3510
        """
3511
        return self
3512
                   
3513

    
3514
     @property
3515
     def node_kind(self):
3516
        """
3517
        node_kind(self)
3518
        Node Kind property. This will be a value such as {@link net.sf.saxon.type.Type#ELEMENT} or {@link net.sf.saxon.type.Type#ATTRIBUTE}.
3519
        There are seven kinds of node: documents, elements, attributes, text, comments, processing-instructions, and namespaces.
3520

    
3521
        Returns:
3522
            int: an integer identifying the kind of node. These integer values are the same as those used in the DOM 
3523
        """
3524
        cdef int kind
3525
        return self.derivednptr.getNodeKind()
3526

    
3527
     @property
3528
     def node_kind_str(self):
3529
        """
3530
        node_kind(self)
3531
        Node Kind property string. This will be a value such as {@link net.sf.saxon.type.Type#ELEMENT} or {@link net.sf.saxon.type.Type#ATTRIBUTE}.
3532
        There are seven kinds of node: documents, elements, attributes, text, comments, processing-instructions, and namespaces.
3533

    
3534
        Returns:
3535
            int: an integer identifying the kind of node. These integer values are the same as those used in the DOM 
3536
        """
3537
        cdef str kind
3538
        cdef int nk = self.derivednptr.getNodeKind()
3539
        if nk == DOCUMENT:
3540
            kind = 'document'
3541
        elif nk == ELEMENT:
3542
            kind = 'element'
3543
        elif nk == ATTRIBUTE:
3544
            kind = 'attribute'
3545
        elif nk == TEXT:
3546
            kind = 'text'
3547
        elif nk == COMMENT:
3548
            kind = 'comment'
3549
        elif nk == PROCESSING_INSTRUCTION:
3550
            kind = 'processing-instruction'
3551
        elif nk == NAMESPACE:
3552
            kind = 'namespace'
3553
        elif nk == UNKNOWN:
3554
            kind = 'unknown'
3555
        else:
3556
            raise ValueError('Unknown node kind: %d' % nk)
3557
        return kind
3558

    
3559
     @property
3560
     def name(self):
3561
        """
3562
        name(self)
3563
        Get the name of the node, as a string in the form of a EQName
3564
        Returns:
3565
            str: the name of the node. In the case of unnamed nodes (for example, text and comment nodes) return None       
3566
        """
3567
        cdef const char* c_string = self.derivednptr.getNodeName()
3568
        if c_string == NULL:
3569
            return None
3570
        else:
3571
            ustring = c_string.decode('UTF-8')
3572
            return ustring 
3573

    
3574
     @property
3575
     def typed_value(self):
3576
        """ 
3577
        typed_value(self)
3578
        Property - get the typed value of this node, as defined in XDM
3579
        Returns:
3580
            PyXdmValue:the typed value. If the typed value is a single atomic value, this will be returne as an instance of {@link XdmAtomicValue}                
3581
        """
3582
        cdef PyXdmValue val = None
3583
        cdef saxoncClasses.XdmValue * xdmValue = self.derivednptr.getTypedValue()
3584
        if xdmValue == NULL:
3585
            return None
3586
        else:
3587
            val = PyXdmValue()
3588
            val.thisvptr = xdmValue
3589
            return val
3590

    
3591
     @property
3592
     def base_uri(self):
3593
        """ 
3594
        base_uri(self)
3595
        Base uri Property. Get the Base URI for the node, that is, the URI used for resolving a relative URI contained in the node.
3596
        This will be the same as the System ID unless xml:base has been used. Where the node does not have a base URI of its own,
3597
        the base URI of its parent node is returned.
3598
        Returns:
3599
            str: String value of the base uri for this node. This may be null if the base URI is unknown, including the case
3600
                 where the node has no parent.
3601
        """
3602
        return make_py_str(self.derivednptr.getBaseUri())
3603

    
3604
     @property
3605
     def string_value(self):
3606
        """
3607
        get_String_value(self)
3608
        Property to get the string value of the node as defined in the XPath data model.
3609

    
3610
        Returns:
3611
            str: The string value of this node
3612

    
3613
        """
3614
        cdef const char* c_string = self.derivednptr.getStringValue()
3615
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
3616
        return ustring
3617

    
3618

    
3619
     def __str__(self):
3620
        """
3621
        __str__(self)
3622
        The string value of the node as defined in the XPath data model
3623
        Returns:
3624
            str: String value of this node
3625
        """
3626
        cdef const char* c_string = self.derivednptr.toString()
3627
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
3628
        return ustring
3629

    
3630
     def __repr__(self):
3631
        """
3632
        ___repr__ 
3633
        """
3634
        cdef const char* c_string = self.derivednptr.toString()
3635
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
3636
        return ustring
3637

    
3638

    
3639

    
3640
     def get_parent(self):
3641
        """
3642
        get_parent(self)
3643
        Get the current node's parent
3644

    
3645
        Returns:
3646
            PyXdmNode: The parent node as PyXdmNode object
3647
        """
3648

    
3649
        cdef PyXdmNode val = PyXdmNode()
3650
        val.derivednptr = val.derivedptr = val.thisvptr = self.derivednptr.getParent()
3651
        return val
3652

    
3653
     def get_attribute_value(self, name):
3654
        """
3655
        getAttribute_value(self, name)
3656
        The name of the required attribute
3657
        
3658
        Args:
3659
            name(str): the eqname of the required attribute
3660

    
3661
        """
3662
        py_value_string = name.encode('UTF-8') if name is not None else None
3663
        cdef char * c_name = py_value_string if name is not None else ""
3664
         
3665
        cdef const char* c_string = self.derivednptr.getAttributeValue(c_name)
3666
        ustring = c_string.decode('UTF-8') if c_string is not NULL else None
3667
                
3668
        return ustring
3669

    
3670
     @property
3671
     def attribute_count(self):
3672
        """
3673
        attribute_count(self)
3674
        Property to get the count of attribute nodes on this XdmNode object. If this current node is not an element node then return 0
3675

    
3676
        Returns:
3677
            int: Count of attribute nodes
3678

    
3679
        """
3680
        return self.derivednptr.getAttributeCount()
3681

    
3682
     @property
3683
     def attributes(self):
3684
        """
3685
        attribute_nodes(self)
3686
        Property to get the attribute nodes as a list of PyXdmNode objects
3687

    
3688
        Returns:
3689
            list[PyXdmNode]: List of PyXdmNode objects
3690
        """
3691
        cdef list nodes = []
3692
        cdef saxoncClasses.XdmNode **n
3693
        cdef int count, i
3694
        cdef PyXdmNode val = None
3695
        count = self.derivednptr.getAttributeCount()
3696
        if count > 0:
3697
            n = self.derivednptr.getAttributeNodes()
3698
            for i in range(count):
3699
                val = PyXdmNode()
3700
                val.derivednptr = val.derivedptr = val.thisvptr = n[i]
3701
                val.derivednptr.incrementRefCount()
3702
                nodes.append(val)
3703

    
3704
        return nodes
3705

    
3706

    
3707
     @property
3708
     def children(self):
3709
        """
3710
        children(self)
3711
        Property to get children of this current node. List of child nodes
3712

    
3713
        Returns:
3714
            list[PyXdmNode]: List of PyXdmNode objects
3715
        """
3716
        cdef list nodes = []
3717
        cdef saxoncClasses.XdmNode **n
3718
        cdef int count, i
3719
        cdef PyXdmNode val = None
3720
        count = self.derivednptr.getChildCount()
3721
        if count > 0:
3722
            n = self.derivednptr.getChildren()
3723
            for i in range(count):
3724
                val = PyXdmNode()
3725
                val.derivednptr = val.derivedptr = val.thisvptr = n[i]
3726
                val.derivednptr.incrementRefCount()
3727
                nodes.append(val)
3728

    
3729
        return nodes
3730

    
3731
      # def getChildCount(self):
3732

    
3733

    
3734
cdef class PyXdmAtomicValue(PyXdmItem):
3735
     """
3736
     The class PyXdmAtomicValue represents an item in an Xath sequence that is an atomic value. The value may belong to any of the
3737
     19 primitive types defined in XML Schema, or to a type derived from these primitive types, or the XPath type xs:untypedAtomic.
3738
     """
3739

    
3740
     cdef saxoncClasses.XdmAtomicValue *derivedaptr      # hold a C++ instance which we're wrapping
3741

    
3742
     def __cinit__(self):
3743
        if type(self) is PyXdmAtomicValue:
3744
            self.derivedaptr = self.derivedptr = self.thisvptr = new saxoncClasses.XdmAtomicValue()
3745
     def __dealloc__(self):
3746
        if self.derivedaptr != NULL and self.derivedaptr != NULL:
3747
            if self.derivedaptr.getRefCount() < 1:
3748
                del self.derivedaptr
3749
            else:
3750
                self.derivedaptr.decrementRefCount()
3751
            
3752

    
3753
     @property
3754
     def primitive_type_name(self):
3755
        """
3756
        get_primitive_type_name()
3757
        Property - Get the primitive type name of the PyXdmAtomicValue
3758
        Returns:
3759
            str: String of the primitive type name
3760

    
3761
        """      
3762
        cdef const char* c_string = self.derivedaptr.getPrimitiveTypeName()
3763
        ustring = c_string.decode('UTF-8')
3764
        return ustring
3765

    
3766

    
3767
     @property
3768
     def boolean_value(self):
3769
        """
3770
        Property which returns the boolean value of the PyXdmAtomicValue
3771

    
3772
        Returns:
3773
            bool: boolean value.
3774

    
3775

    
3776
        """
3777
        return self.derivedaptr.getBooleanValue()
3778

    
3779
     @property
3780
     def double_value(self):
3781
        """
3782
        Property which is returns the double value of the PyXdmAtomicValue if it can be converted.
3783

    
3784
        Returns:
3785
            double: Double value of the Xdm object
3786

    
3787
        """
3788
        
3789
        return self.derivedaptr.getDoubleValue()
3790

    
3791
     @property
3792
     def head(self):
3793
        """
3794
        head(self)
3795
        Property to get the first item in the sequence. This would be the PyXdmAtomicValue itself as there is only one item in the sequence
3796

    
3797
        Returns:
3798
            PyXdmAtomicValue: The PyXdmAtomic or None if the sequence is empty
3799

    
3800
        """
3801
        return self
3802
    
3803

    
3804
     @property
3805
     def integer_value(self):
3806
        """
3807
        Property which is returns the int value of the PyXdmAtomicValue if it can be converted.
3808

    
3809
        Returns:
3810
            int: Int value of the Xdm object
3811

    
3812
        """
3813
        
3814
        return self.derivedaptr.getLongValue()
3815

    
3816

    
3817
     @property
3818
     def string_value(self):
3819
        """
3820
        Property which returns the string value of the PyXdmAtomicValue
3821
        Returns:
3822
            str: String value of the Xdm object
3823
        """
3824
        cdef const char* c_string = self.derivedaptr.getStringValue()
3825
        ustring = c_string.decode('UTF-8')
3826
        return ustring
3827

    
3828

    
3829
     def __str__(self):
3830
        """
3831
        __str__(self)
3832
        The string value of the node as defined in the XPath data model
3833
        Returns:
3834
            str: String value of this node
3835
        """
3836
        cdef const char* c_string = self.derivedaptr.getStringValue()
3837
        ustring = c_string.decode('UTF-8')
3838
        return ustring
3839

    
3840
     def __repr__(self):
3841
        """
3842
        ___repr__ 
3843
        """
3844
        cdef const char* c_string = self.derivedaptr.getStringValue()
3845
        ustring = c_string.decode('UTF-8')
3846
        return ustring
3847

    
(8-8/11)