Project

Profile

Help

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

he / tags / 9.6.0.7 / samples / cs / XQueryExamples.cs @ c74fd4aa

1
using System;
2
using System.IO;
3
using System.Collections;
4
using System.Xml;
5
using Saxon.Api;
6

    
7

    
8
/**
9
 * Some examples to show how the Saxon XQuery API should be used
10
 */
11
public class XQueryExamples {
12

    
13
    /**
14
     * Class is not instantiated, so give it a private constructor
15
     */
16
    private XQueryExamples() {
17
    }
18

    
19
    /**
20
     * Method main. First argument is the name of the test to be run (defaults to "all").
21
     * Second argument is the samples directory: defaults to %HOME%/samples/
22
     */
23
    public static void Main(String[] argv) {
24

    
25
        String test = "all";
26

    
27
        if (argv.Length > 0) {
28
            test = argv[0];
29
        }
30

    
31
        String samplesDir;
32

    
33
        if (argv.Length > 1) {
34
            samplesDir = argv[1];
35
        } else {
36
            String home = Environment.GetEnvironmentVariable("SAXON_HOME");
37
            if (home == null) {
38
                Console.WriteLine("No input directory supplied, and SAXON_HOME is not set");
39
                return;
40
            } else {
41
                if (home.EndsWith("/") || home.EndsWith("\\")) {
42
                    samplesDir = home + "samples/";
43
                } else {
44
                    samplesDir = home + "/samples/";
45
                }
46
            }
47
        }
48

    
49
        String inputFile = samplesDir + "data/books.xml";
50

    
51
        if (test == "all" || test == "toStreamResult") {
52
            Console.WriteLine("\n\n==== toStreamResult ====");
53

    
54
            try {
55
                ExampleToStreamResult();
56
            } catch (Exception ex) {
57
                handleException(ex);
58
            }
59
        }
60

    
61
        if (test == "all" || test == "toSingleton") {
62
            Console.WriteLine("\n\n==== toSingleton ====");
63

    
64
            try {
65
                ExampleToSingleton();
66
            } catch (Exception ex) {
67
                handleException(ex);
68
            }
69
        }
70

    
71
        if (test == "all" || test == "toDOM") {
72
            Console.WriteLine("\n\n==== toDOM ====");
73

    
74
            try {
75
                ExampleToDOM(inputFile);
76
            } catch (Exception ex) {
77
                handleException(ex);
78
            }
79
        }
80

    
81
        if (test == "all" || test == "toXDM") {
82
            Console.WriteLine("\n\n==== toXDM ====");
83

    
84
            try {
85
                ExampleToXDM(inputFile);
86
            } catch (Exception ex) {
87
                handleException(ex);
88
            }
89
        }
90

    
91
        if (test == "all" || test == "toSequence") {
92
            Console.WriteLine("\n\n==== toSequence ====");
93

    
94
            try {
95
                ExampleToSequence();
96
            } catch (Exception ex) {
97
                handleException(ex);
98
            }
99
        }
100

    
101
        if (test == "all" || test == "fromXmlReader") {
102
            Console.WriteLine("\n\n==== fromXmlReader ====");
103

    
104
            try {
105
                ExampleFromXmlReader(inputFile);
106
            } catch (Exception ex) {
107
                handleException(ex);
108
            }
109
        }
110

    
111
        if (test == "all" || test == "toSerializedSequence") {
112
            Console.WriteLine("\n\n==== toSerializedSequence ====");
113

    
114
            try {
115
                ExampleToSerializedSequence(inputFile);
116
            } catch (Exception ex) {
117
                handleException(ex);
118
            }
119
        }
120

    
121
        if (test == "all" || test == "toWrappedSequence") {
122
            Console.WriteLine("\n\n==== toWrappedSequence ====");
123

    
124
            try {
125
                ExampleToWrappedSequence();
126
            } catch (Exception ex) {
127
                handleException(ex);
128
            }
129
        }
130

    
131
        if (test == "all" || test == "toHTMLFile") {
132
            Console.WriteLine("\n\n==== toHTMLFile ====");
133

    
134
            try {
135
                ExampleToHTMLFile();
136
            } catch (Exception ex) {
137
                handleException(ex);
138
            }
139
        }
140

    
141
        if (test == "all" || test == "withParam") {
142
            Console.WriteLine("\n\n==== withParam ====");
143

    
144
            try {
145
                ExampleWithParam();
146
            } catch (Exception ex) {
147
                handleException(ex);
148
            }
149
        }
150

    
151
        if (test == "all" || test == "multiModule") {
152
            Console.WriteLine("\n\n==== multiModule ====");
153

    
154
            try {
155
                ExampleMultiModule();
156
            } catch (Exception ex) {
157
                handleException(ex);
158
            }
159
        }
160

    
161
        if (test == "all" || test == "pipeline") {
162
            Console.WriteLine("\n\n==== pipeline ====");
163

    
164
            try {
165
                ExamplePipeline();
166
            } catch (Exception ex) {
167
                handleException(ex);
168
            }
169
        }
170

    
171
        if (test == "all" || test == "extra") {
172
            Console.WriteLine("\n\n==== extra ====");
173

    
174
            try {
175
                ExampleExtra();
176
            } catch (Exception ex) {
177
                handleException(ex);
178
            }
179
        }
180

    
181

    
182
    }
183

    
184
    /**
185
     * Show a query producing a document as its result and serializing this
186
     * to a FileStream
187
     */
188

    
189
    public static void ExampleToStreamResult() {
190
        Processor processor = new Processor();
191
        XQueryCompiler compiler = processor.NewXQueryCompiler();
192
        compiler.BaseUri = "http://www.saxonica.com/";
193
        compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");
194
        XQueryExecutable exp = compiler.Compile("<saxon:example>{static-base-uri()}</saxon:example>");
195
        XQueryEvaluator eval = exp.Load();
196
        Serializer qout = new Serializer();
197
        qout.SetOutputProperty(Serializer.METHOD, "xml");
198
        qout.SetOutputProperty(Serializer.INDENT, "yes");
199
        qout.SetOutputProperty(Serializer.SAXON_INDENT_SPACES, "1");
200
        qout.SetOutputStream(new FileStream("testoutput.xml", FileMode.Create, FileAccess.Write));
201
        eval.Run(qout);
202
    }
203

    
204
    /**
205
     * Show a query producing a single atomic value as its result and returning the value
206
     * to the Java application
207
     */
208

    
209
    public static void ExampleToSingleton() {
210
        Processor processor = new Processor();
211
        XQueryCompiler compiler = processor.NewXQueryCompiler();
212
        XQueryExecutable exp = compiler.Compile("avg(for $i in 1 to 10 return $i * $i)");
213
        XQueryEvaluator eval = exp.Load();
214
        XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
215
        Console.WriteLine("Result type: " + result.Value.GetType());
216
        Console.WriteLine("Result value: " + (decimal)result.Value);
217
    }
218

    
219
    /**
220
     * Show a query taking a DOM as its input and producing a DOM as its output. 
221
     */
222

    
223
    public static void ExampleToDOM(String inputFileName) {
224
        Processor processor = new Processor();
225

    
226
        XmlDocument input = new XmlDocument();
227
        input.Load(inputFileName);
228
        XdmNode indoc = processor.NewDocumentBuilder().Build(new XmlNodeReader(input));
229

    
230
        XQueryCompiler compiler = processor.NewXQueryCompiler();
231
        XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>");
232
        XQueryEvaluator eval = exp.Load();
233
        eval.ContextItem = indoc;
234
        DomDestination qout = new DomDestination();
235
        eval.Run(qout);
236
        XmlDocument outdoc = qout.XmlDocument;
237
        Console.WriteLine(outdoc.OuterXml);
238

    
239
    }
240

    
241
    /**
242
     * Show a query taking a Saxon tree as its input and producing a Saxon tree as its output. 
243
     */
244

    
245
    public static void ExampleToXDM(String inputFileName) {
246
        Processor processor = new Processor();
247

    
248
        DocumentBuilder loader = processor.NewDocumentBuilder();
249
        loader.BaseUri = new Uri(inputFileName);
250
        XdmNode indoc = loader.Build(
251
                new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
252

    
253
        XQueryCompiler compiler = processor.NewXQueryCompiler();
254
        XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>");
255
        XQueryEvaluator eval = exp.Load();
256
        eval.ContextItem = indoc;
257
        XdmDestination qout = new XdmDestination();
258
        eval.Run(qout);
259
        XdmNode outdoc = qout.XdmNode;
260
        Console.WriteLine(outdoc.OuterXml);
261

    
262
    }
263

    
264
    /**
265
     * Show a query producing a sequence as its result and returning the sequence
266
     * to the Java application in the form of an iterator. For each item in the
267
     * result, its string value is output.
268
     */
269

    
270
    public static void ExampleToSequence() {
271
        Processor processor = new Processor();
272
        XQueryCompiler compiler = processor.NewXQueryCompiler();
273
        XQueryExecutable exp = compiler.Compile("for $i in 1 to 10 return $i * $i");
274
        XQueryEvaluator eval = exp.Load();
275
        XdmValue value = eval.Evaluate();
276
        IEnumerator e = value.GetEnumerator();
277
        while (e.MoveNext()) {
278
            XdmItem item = (XdmItem)e.Current;
279
            Console.WriteLine(item.ToString());
280
        }
281

    
282
    }
283

    
284
    /**
285
     * Show a query reading an input document using an XmlReader (the .NET XML parser)
286
     */
287

    
288
    public static void ExampleFromXmlReader(String inputFileName) {
289
        Processor processor = new Processor();
290

    
291
        XmlTextReader reader = new XmlTextReader(inputFileName,
292
            new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
293
        reader.Normalization = true;
294

    
295
        // add a validating reader - not to perform validation, but to expand entity references
296
        XmlValidatingReader validator = new XmlValidatingReader(reader);
297
        validator.ValidationType = ValidationType.None;
298

    
299
        XdmNode doc = processor.NewDocumentBuilder().Build(validator);
300

    
301
        XQueryCompiler compiler = processor.NewXQueryCompiler();
302
        XQueryExecutable exp = compiler.Compile("/");
303
        XQueryEvaluator eval = exp.Load();
304
        eval.ContextItem = doc;
305
        Serializer qout = new Serializer();
306
        qout.SetOutputProperty(Serializer.METHOD, "xml");
307
        qout.SetOutputProperty(Serializer.INDENT, "yes");
308
        qout.SetOutputStream(new FileStream("testoutput2.xml", FileMode.Create, FileAccess.Write));
309
        eval.Run(qout);
310

    
311
    }
312

    
313
    /**
314
     * Show a query producing a sequence as its result and returning the sequence
315
     * to the Java application in the form of an iterator. The sequence is then
316
     * output by serializing each item individually, with each item on a new line.
317
     */
318

    
319
    public static void ExampleToSerializedSequence(String inputFileName) {
320
        Processor processor = new Processor();
321

    
322
        XmlTextReader reader = new XmlTextReader(inputFileName,
323
            new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
324
        reader.Normalization = true;
325

    
326
        // add a validating reader - not to perform validation, but to expand entity references
327
        XmlValidatingReader validator = new XmlValidatingReader(reader);
328
        validator.ValidationType = ValidationType.None;
329

    
330
        XdmNode doc = processor.NewDocumentBuilder().Build(reader);
331

    
332
        XQueryCompiler compiler = processor.NewXQueryCompiler();
333
        XQueryExecutable exp = compiler.Compile("//ISBN");
334
        XQueryEvaluator eval = exp.Load();
335
        eval.ContextItem = doc;
336

    
337
        foreach (XdmNode node in eval) {
338
            Console.WriteLine(node.OuterXml);
339
        }
340
    }
341

    
342
    /**
343
     * Show a query producing a sequence as its result and returning the sequence
344
     * to the Java application in the form of an iterator. The sequence is then
345
     * output by wrapping the items in a document, with wrapping elements indicating
346
     * the type of each item, and serializing the resulting document.
347
     */
348

    
349
    public static void ExampleToWrappedSequence() {
350
        //final Processor processor = new Processor();
351
        //final StaticQueryContext sqc = new StaticQueryContext(processor);
352
        //final XQueryExpression exp = sqc.compileQuery("<doc><chap><a>3</a></chap></doc>//a, <b>4</b>, attribute c {5}, 19");
353
        //Properties props = new Properties();
354
        //props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
355
        //props.setProperty(OutputKeys.INDENT, "yes");
356

    
357
        //final DynamicQueryContext dynamicContext = new DynamicQueryContext(processor);
358
        //final SequenceIterator iter = exp.iterator(dynamicContext);
359
        //final DocumentInfo doc = QueryResult.wrap(iter, processor);
360
        //QueryResult.serialize(doc, new StreamResult(System.out), props, processor);
361
    }
362

    
363

    
364
    /**
365
     * Show how to run a query that is read from a file and that serializes its output
366
     * as HTML to another file. The input to the query (the initial value of the context
367
     * node) is supplied as the content of another file.
368
     */
369

    
370
    public static void ExampleToHTMLFile() {
371
        //final Processor processor = new Processor();
372
        //final StaticQueryContext sqc = new StaticQueryContext(processor);
373
        //final XQueryExpression exp = sqc.compileQuery(new FileReader("query/books-to-html.xq"));
374
        //final DynamicQueryContext dynamicContext = new DynamicQueryContext(processor);
375
        //dynamicContext.setContextItem(sqc.buildDocument(new StreamSource("data/books.xml")));
376
        //final Properties props = new Properties();
377
        //props.setProperty(OutputKeys.METHOD, "html");
378
        //props.setProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD HTML 4.01 Transitional//EN");
379
        //exp.run(dynamicContext, new StreamResult(new File("booklist.html")), props);
380
    }
381

    
382
    /**
383
     * Show a query that takes a parameter (external variable) as input.
384
     * The query produces a single atomic value as its result and returns the value
385
     * to the Java application. For the types of value that may be returned, and
386
     * their mapping to XPath data types, see {@link XPathEvaluator#Evaluate}
387
     */
388

    
389
    public static void ExampleWithParam() {
390
        Processor processor = new Processor();
391
        XQueryCompiler compiler = processor.NewXQueryCompiler();
392
        compiler.DeclareNamespace("p", "http://saxon.sf.net/ns/p");
393
        XQueryExecutable exp = compiler.Compile(
394
                "declare variable $p:in as xs:integer external; $p:in * $p:in");
395
        XQueryEvaluator eval = exp.Load();
396
        eval.SetExternalVariable(new QName("http://saxon.sf.net/ns/p", "p:in"), new XdmAtomicValue(12));
397
        XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
398
        Console.WriteLine("Result type: " + result.Value.GetType());
399
        Console.WriteLine("Result value: " + (long)result.Value);
400

    
401
    }
402

    
403
    /**
404
     * Show a query consisting of two modules, using a QueryResolver to resolve
405
     * the "import module" declaration
406
     */
407

    
408
    public static void ExampleMultiModule() {
409

    
410
        String mod1 = "import module namespace m2 = 'http://www.example.com/module2';" +
411
                      "m2:square(3)";
412

    
413
        String mod2 = "module namespace m2 = 'http://www.example.com/module2';" +
414
                      "declare function m2:square($p) { $p * $p };";
415

    
416
        Processor processor = new Processor();
417
        XQueryCompiler compiler = processor.NewXQueryCompiler();
418

    
419
        InlineModuleResolver resolver = new InlineModuleResolver();
420
        resolver.AddModule(new Uri("http://www.example.com/module2"), mod2);
421
        compiler.QueryResolver = resolver;
422
        XQueryExecutable exp = compiler.Compile(mod1);
423
        XQueryEvaluator eval = exp.Load();
424

    
425
        XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
426
        Console.WriteLine("Result type: " + result.Value.GetType());
427
        Console.WriteLine("Result value: " + (long)result.Value);
428

    
429
    }
430

    
431
    // A simple QueryResolver designed to show that the actual query
432
    // text can come from anywhere: in this case, the resolver maintains
433
    // a simple mapping of module URIs onto strings.
434

    
435
    public class InlineModuleResolver : IQueryResolver {
436

    
437
        private Hashtable modules = new Hashtable();
438

    
439
        public void AddModule(Uri moduleName, String moduleText) {
440
            modules.Add(moduleName, moduleText);
441
        }
442

    
443
        public Uri[] GetModules(String moduleUri, Uri baseUri, String[] locationHints) {
444
            Uri[] result = { new Uri(moduleUri) };
445
            return result;
446
        }
447

    
448
        public Object GetEntity(Uri absoluteUri) {
449
            return modules[absoluteUri];
450
        }
451
    }
452

    
453
    /**
454
     * Show how to run two queries in tandem. The second query is applied to the
455
     * results of the first.
456
     */
457

    
458
    public static void ExamplePipeline() {
459
        //final Processor processor = new Processor();
460

    
461
        // Compile the first query
462
        //final StaticQueryContext sqc1 = new StaticQueryContext(processor);
463
        //final XQueryExpression exp1 = sqc1.compileQuery("declare variable $in as xs:integer external;" +
464
        //        "document{ <a>{$in * $in}</a> }");
465

    
466
        // Compile the second query (each query should have its own static context)
467
        //final StaticQueryContext sqc2 = new StaticQueryContext(processor);
468
        //final XQueryExpression exp2 = sqc2.compileQuery("/a + 5");
469

    
470
        // Run the first query
471
        //final DynamicQueryContext dynamicContext = new DynamicQueryContext(processor);
472
        //dynamicContext.setParameter("in", new Long(3));
473
        //final NodeInfo doc = (NodeInfo)exp1.evaluateSingle(dynamicContext);
474

    
475
        // Run the second query
476
        //dynamicContext.clearParameters();
477
        //dynamicContext.setContextItem(doc);
478
        //final Object result = exp2.evaluateSingle(dynamicContext);
479
        //Console.WriteLine("3*3 + 5 = " + result);
480
        // The result is actually a java.lang.Double
481
    }
482

    
483
    /**
484
     * Show how to run two queries in tandem. The second query is applied to the
485
     * results of the first.
486
     */
487

    
488
    public static void ExampleExtra() {
489
        // place-holder to add user-defined examples for testing
490
        Processor processor = new Processor();
491
        XQueryCompiler compiler = processor.NewXQueryCompiler();
492
        XQueryExecutable exp = compiler.Compile(@"<out>{matches('ABC', '\p{IsBasicLatin}*')}</out>");
493
        XQueryEvaluator eval = exp.Load();
494
        DomDestination dest = new DomDestination();
495
        eval.Run(dest);
496
        Console.WriteLine(dest.XmlDocument.OuterXml);
497
    }
498

    
499

    
500

    
501

    
502
    /**
503
     * Handle an exception thrown while running one of the examples
504
     *
505
     * @param ex the exception
506
     */
507
    private static void handleException(Exception ex) {
508
        Console.WriteLine("EXCEPTION: " + ex);
509
        Console.WriteLine(ex.StackTrace);
510
    }
511

    
512
}
513

    
514
//
515
// The contents of this file are subject to the Mozilla Public License Version 1.0 (the "License");
516
// you may not use this file except in compliance with the License. You may obtain a copy of the
517
// License at http://www.mozilla.org/MPL/
518
//
519
// Software distributed under the License is distributed on an "AS IS" basis,
520
// WITHOUT WARRANTY OF ANY KIND, either express or implied.
521
// See the License for the specific language governing rights and limitations under the License.
522
//
523
// The Original Code is: all this file.
524
//
525
// The Initial Developer of the Original Code is Michael H. Kay.
526
//
527
// Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved.
528
//
529
// Contributor(s): none.
530
//
(4-4/5)