Project

Profile

Help

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

he / src / test / nunit / SaxonNUnit / SaxonNUnit / TestDocumentBuilder.cs @ 3df04590

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Xml;
5
using System.IO;
6
using Saxon.Api;
7
using NUnit.Framework;
8
using System.Collections;
9

    
10

    
11

    
12
namespace SaxonNUnit
13
{
14

    
15
    /**
16
        * NUnit tests for the s9api DocumentBuilder
17
    */
18
    class TestDocumentBuilder
19
    {
20

    
21
        [Test]
22
        public void TestSaxSourceDTDValidation()
23
        {
24
            String validXML = "<!DOCTYPE a [<!ELEMENT a EMPTY>]><a/>";
25
            String invalidXML = "<!DOCTYPE a [<!ELEMENT a (b+)>]><a/>";
26
            DocumentBuilder builder = new Processor(false).NewDocumentBuilder();
27
            builder.BaseUri = new Uri("http://www.example.com");
28
            builder.DtdValidation = true;
29

    
30
            StringReader sr = new StringReader(validXML);
31
           
32
            try
33
            {
34
                XdmNode d = builder.Build(sr);
35
                Assert.NotNull(d);
36
            }
37
            catch (Exception e)
38
            {
39
                Assert.Fail(e.Message);
40
            }
41

    
42
            sr = new StringReader(invalidXML);
43
         
44
            try
45
            {
46
                XdmNode d = builder.Build(sr);
47
                Assert.Fail("invalid document parsed without error");
48
            }
49
            catch (Exception e)
50
            {
51
                // expected failure;
52
            }
53

    
54
            builder.DtdValidation = false;
55
            sr = new StringReader(invalidXML);
56
            try
57
            {
58
                XdmNode d = builder.Build(sr);
59
                Assert.NotNull(d);
60
            }
61
            catch (Exception e)
62
            {
63
                Assert.Fail("Parsing failed but validation was not requested: " + e.Message);
64
            }
65

    
66
        }
67

    
68
        [Test]
69
        public void TestQNameValue() {
70
            try {
71
                var path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, System.AppDomain.CurrentDomain.RelativeSearchPath ?? "");
72

    
73
                // Create a Processor instance.
74
                Processor processor = new Saxon.Api.Processor(new StreamReader(ConfigTest.NUNIT_DATA_DIR + @"\saxon.config").BaseStream);
75
                Assert.NotNull(processor);
76
            }
77
            catch (Exception ex) {
78
                Assert.Fail(ex.Message);
79
            }
80
            }
81
        [Test]
82
        public void TesStringReaderSource()
83
        {
84
            try
85
            {
86
                StringReader sr = new StringReader("<doc/>");
87
                DocumentBuilder builder = new Processor(false).NewDocumentBuilder();
88
                builder.BaseUri = new Uri("http://www.example.com");
89
                XdmNode d = builder.Build(sr);
90
                Assert.NotNull(d);
91
            }
92
            catch (javax.xml.transform.TransformerException e)
93
            {
94
                Assert.Fail(e.Message);
95
            }
96
        }
97

    
98
        [Test]
99
        public void TesXmlReaderSource()
100
        {
101
            try
102
            {
103
                XmlReader xml = XmlReader.Create(new StringReader("<doc/>"));
104
                DocumentBuilder builder = new Processor(false).NewDocumentBuilder();
105
                builder.BaseUri = new Uri("http://www.example.com");
106
                XdmNode d = builder.Build(xml);
107
                Assert.NotNull(d);
108
            }
109
            catch (javax.xml.transform.TransformerException e)
110
            {
111
                Assert.Fail(e.Message);
112
            }
113
        }
114

    
115
        [Test]
116
        public void TestNamespaceNodes()
117
        {
118
            try
119
            {
120
                StringReader sr = new StringReader("<doc xmlns='abc.uri'><e xmlns:a='one.uri' xmlns:b='two.uri'/></doc>");
121
                XmlReader xml = XmlReader.Create(sr);
122
                Processor processor = new Processor(false);
123
                DocumentBuilder builder = processor.NewDocumentBuilder();
124
                XdmNode d = builder.Build(xml);
125
                Assert.NotNull(d);
126
                XPathSelector xp = processor.NewXPathCompiler().Compile("/*/*").Load();
127
                xp.ContextItem = d;
128
                XdmNode e = (XdmNode)xp.EvaluateSingle();
129
                Assert.NotNull(e);
130
                IEnumerator nsIter = e.EnumerateAxis(XdmAxis.Namespace);
131
                Dictionary<String, String> nsBindings = new Dictionary<String, String>();
132
                while (nsIter.MoveNext())
133
                {
134
                    XdmNode ns = (XdmNode)nsIter.Current;
135
                    Console.WriteLine(ns.ToString());
136
                    nsBindings.Add((ns.NodeName == null ? "" : ns.NodeName.LocalName), ns.StringValue);
137
                }
138
                Assert.True(nsBindings.Count() == 4);
139

    
140

    
141
            }
142
            catch (Exception e)
143
            {
144
                Assert.Fail(e.Message);
145
            }
146
        }
147

    
148
        [Test]
149
        public void TestDOMElementNode()
150
        {
151
            try
152
            {
153

    
154
                String sr = "<?xml version='1.0'?> \n" +
155
                        "<Document> <e> <f/><f/> </e> </Document>";
156

    
157
                // Read an XML file to a DOM
158
                XmlDocument xml = new XmlDocument();
159
                xml.LoadXml(sr);
160

    
161
                Processor proc = new Processor(false);
162
                XsltCompiler comp = proc.NewXsltCompiler();
163
                XsltExecutable exec = comp.Compile(new Uri(ConfigTest.NUNIT_DATA_DIR + "identity.xsl"));
164
                XsltTransformer xsl = exec.Load();
165
                DocumentBuilder builder = proc.NewDocumentBuilder();
166
                XdmNode node = builder.Build(xml);
167
                xsl.InitialContextNode = node;
168
                StringWriter writer = new StringWriter();
169
                Serializer outi = proc.NewSerializer(writer);
170

    
171
                xsl.Run(outi);
172
                Assert.True(writer.ToString().Contains("<f/>"), "");
173
            }
174
            catch (Exception e)
175
            {
176
                Assert.Fail(e.Message);
177
            }
178
        }
179

    
180

    
181
        /**
182
         * Test that when a document is loaded from multiple external entities, the base URIs of
183
         * elements are preserved
184
        */
185
        [Test]
186
        public void TestBaseUriFromEntities()
187
        {
188
            try
189
            {
190

    
191
                Processor processor = new Processor(false);
192
                XmlReaderSettings settings = new XmlReaderSettings();
193
                settings.DtdProcessing = DtdProcessing.Parse;
194
                var source = File.OpenRead(ConfigTest.RESOURCES_DIR + "book-wrapper.xml");
195

    
196
                DocumentBuilder builder = processor.NewDocumentBuilder();
197

    
198
                builder.BaseUri = new Uri(ConfigTest.RESOURCES_DIR + "book-wrapper.xml");
199
                XdmNode d = builder.Build(source);
200
                XPathCompiler xpc = processor.NewXPathCompiler();
201
                XPathSelector s = xpc.Compile("distinct-values(//*/base-uri())").Load();
202
                s.ContextItem = d;
203
                XdmValue v = s.Evaluate();
204
                Assert.True(v.Count == 3, "3 distinct base URIs");
205
            }
206
            catch (javax.xml.transform.TransformerException e)
207
            {
208
                Assert.Fail(e.Message);
209
            }
210
        }
211

    
212
        //loads input xml file and returns XDM Node
213
        static XdmNode GetXdmNode(Uri inputFile)
214
        {
215
            Processor processor = new Processor();
216
            Uri storeInputFileForComparison = inputFile;
217

    
218
            //regular node creation with passed uri - throws MalformedURIException as already reported
219
            XdmNode inputXdmNode = processor.NewDocumentBuilder().Build(inputFile);
220

    
221
            inputFile = new Uri("file:///" + ConfigTest.NUNIT_DATA_DIR + "\\test test\\books.xml");
222

    
223
            //new node creation with overwritten uri object with the same value - throws also MalformedURIException
224
            XdmNode nodeWithOverwrittenInputFile = processor.NewDocumentBuilder().Build(inputFile);
225

    
226
            //compare new created uri with passed one:
227
            bool equal1 = storeInputFileForComparison == inputFile;         //returns true
228
            bool equal2 = storeInputFileForComparison.Equals(inputFile);    //returns also true
229

    
230
            Uri newInputUriEscaped = new Uri("file:///" + ConfigTest.NUNIT_DATA_DIR + "\\test test\\books.xml", true);
231

    
232
            bool equal3 = storeInputFileForComparison.Equals(newInputUriEscaped);    //returns true
233

    
234
            //new node creation with new uri object with the same value - throws also MalformedURIException
235
            XdmNode nodeWithUnescapedNewInputUri = processor.NewDocumentBuilder().Build(newInputUriEscaped);
236

    
237
            Uri newInputUriUnescaped = new Uri("file:///" + ConfigTest.NUNIT_DATA_DIR + "\\test test\\books.xml", false);
238

    
239
            bool equal4 = storeInputFileForComparison.Equals(newInputUriUnescaped);    //returns true
240

    
241
            //new node creation with new uri object with the same value - throws also MalformedURIException
242
            XdmNode nodeWithNewInputUri = processor.NewDocumentBuilder().Build(newInputUriUnescaped);
243

    
244
            Uri twoSlashesInsteadOfAtSign = new Uri("file:///" + ConfigTest.NUNIT_DATA_DIR + "\\test test\\books.xml");
245

    
246
            bool equal5 = storeInputFileForComparison.Equals(twoSlashesInsteadOfAtSign);    //returns true
247

    
248
            //throws MalformedURIException
249
            XdmNode nodeWithTwoSlashesInsteadOfAtSign = processor.NewDocumentBuilder().Build(twoSlashesInsteadOfAtSign);
250

    
251
            Uri usingFileScheme = new Uri("file:///" + ConfigTest.NUNIT_DATA_DIR + "\\test test\\books.xml");
252

    
253
            //throws MalformedURIException
254
            XdmNode nodeWithFileScheme = processor.NewDocumentBuilder().Build(usingFileScheme);
255

    
256
            Uri differentPath = new Uri("file:///" + ConfigTest.NUNIT_DATA_DIR + "\\test test\\Test Test.xml");
257

    
258
            bool equal6 = storeInputFileForComparison.Equals(differentPath);    //returns false due to different path
259

    
260
            //throws MalformedURIException
261
            XdmNode nodeWithDifferentPath = processor.NewDocumentBuilder().Build(differentPath);
262

    
263
            Uri letsCheckIfUriIsValidForDotNet;
264
            if (Uri.TryCreate("file:///" + ConfigTest.NUNIT_DATA_DIR + "test test\\books.xml", UriKind.Absolute, out letsCheckIfUriIsValidForDotNet)) //returns true
265
            {
266
                // the url is valid
267
            }
268

    
269
            Uri newUri = new Uri("file:///" + ConfigTest.NUNIT_DATA_DIR + "\\Test.xml");   //HostType is also "IPv6HostType | UncHostType" 
270

    
271
            //throws MalformedURIException
272
            return processor.NewDocumentBuilder().Build(inputFile);
273
        }
274

    
275
        [Test]
276
        public void TestUriWithSpace2()
277
        {
278
             var uriBuilder = new UriBuilder(Uri.EscapeUriString("file:///" + ConfigTest.DATA_DIR2 + "test test//test test.xml"));
279

    
280
            Uri uri = uriBuilder.Uri;// new Uri(uriBuilder);
281
            GetXdmNode(uri);
282
        }
283

    
284
        [Test]
285
        public void TestUriWithSpace()
286
        {
287
            try
288
            {
289

    
290
                Processor processor = new Processor();
291
                var uriBuilder = new UriBuilder("file:///"+ConfigTest.DATA_DIR + "book-wrapper.xml");
292

    
293
                Uri uri = uriBuilder.Uri;// new Uri("file:///C:/test test/books.xml");
294

    
295
                XdmNode node = processor.NewDocumentBuilder().Build(uri);
296

    
297

    
298
                XPathCompiler xpc = processor.NewXPathCompiler();
299
                XPathSelector s = xpc.Compile("distinct-values(//*/base-uri())").Load();
300
                s.ContextItem = node;
301
                XdmValue v = s.Evaluate();
302
                Assert.True(v.Count == 3, "3 distinct base URIs");
303
            }
304
            catch (Exception e)
305
            {
306
                Assert.Fail(e.Message);
307
            }
308
        }
309

    
310

    
311
        /**
312
    * Test that when a document with multiple base URIs is copied, the base URIs of
313
    * elements are preserved
314
         * This is for Saxon 9.6. at present there is not a Build method that can handle a Saxon.Api.XdmNode
315
    */
316
        // [Test]
317
        public void TestBaseUriFromCopy()
318
        {
319

    
320
            try {
321
                Processor processor = new Processor(false);
322
                XmlReaderSettings settings = new XmlReaderSettings();
323
                settings.DtdProcessing = DtdProcessing.Parse;
324
                var source = File.OpenRead(ConfigTest.RESOURCES_DIR + "book-wrapper.xml");
325
                DocumentBuilder builder = processor.NewDocumentBuilder();
326
                builder.TreeModel = TreeModel.TinyTree;
327
                XdmNode d = builder.Build(source);
328
                builder.TreeModel = TreeModel.LinkedTree;
329
                XPathCompiler xpc = processor.NewXPathCompiler();
330
                XPathSelector s = xpc.Compile("distinct-values(//*/base-uri())").Load();
331
                s.ContextItem = d;
332
                XdmValue v = s.Evaluate();
333
                Assert.True(v.Count == 3, "3 distinct base URIs");
334
            } catch (Exception e)
335
            {
336
                Assert.Fail(e.Message);
337
            }
338
 }
339

    
340

    
341
        /**
342
            * Test that when a document is loaded from multiple external entities, the base URIs of
343
            * elements are preserved
344
            */
345
        [Test]
346
        public void TestBaseUriOfAttribute()
347
        {
348
            try
349
            {
350
                Processor processor = new Processor(false);
351
                XmlReaderSettings settings = new XmlReaderSettings();
352
                settings.DtdProcessing = DtdProcessing.Parse;
353
                var source = File.OpenRead(ConfigTest.RESOURCES_DIR + "book-wrapper.xml");
354
                DocumentBuilder builder = processor.NewDocumentBuilder();
355
                builder.BaseUri = new Uri(ConfigTest.RESOURCES_DIR + "book-wrapper.xml");
356
                XdmNode d = builder.Build(source);
357
                XPathCompiler xpc = processor.NewXPathCompiler();
358
                XPathSelector s = xpc.Compile("//@CODE").Load();
359
                s.ContextItem = d;
360
                foreach (XdmItem i in s.Evaluate())
361
                {
362
                    Assert.True(((XdmNode)i).BaseUri.ToString().EndsWith("categories.xml"), "baseURI");
363
                }
364
            }
365
            catch (javax.xml.transform.TransformerException e)
366
            {
367
                Assert.Fail(e.Message);
368
            }
369
        }
370

    
371
      
372

    
373

    
374
        /**
375
        * Test document builder with document projection
376
         * This test case will be for Saxon 9.6
377
        */
378
        [Test]
379
        public void TestProjection001()
380
        {
381
            try
382
            {
383

    
384
                Processor processor = new Processor(true);
385
                XmlReaderSettings settings = new XmlReaderSettings();
386
                settings.DtdProcessing = DtdProcessing.Parse;
387
                var source = File.OpenRead(ConfigTest.RESOURCES_DIR + "book-wrapper.xml");
388

    
389
                XQueryCompiler xpc = processor.NewXQueryCompiler();
390
                XQueryExecutable exp = xpc.Compile("<out>{//CATEGORY}</out>");
391

    
392
                DocumentBuilder builder = processor.NewDocumentBuilder();
393
                builder.BaseUri = new Uri(ConfigTest.RESOURCES_DIR + "book-wrapper.xml");
394
                builder.DocumentProjectionQuery = exp;
395
                builder.TreeModel = TreeModel.TinyTree;
396
                XdmNode doc = builder.Build(source);
397

    
398

    
399
                // Test that the projected doc contains the CATEGORY elements
400

    
401
                StringWriter sw = new StringWriter();
402
                Serializer destination = processor.NewSerializer();
403
                destination.SetOutputWriter(sw);
404
                XQueryEvaluator eval = exp.Load();
405
                eval.ContextItem = doc;
406
                eval.Run(destination);
407

    
408
                Assert.True(sw.ToString().Contains("CODE=\"P\" DESC=\"Paperback\""), "contains CAT");
409

    
410
                // Test that the projected doc omits the ITEM elements
411

    
412
                exp = xpc.Compile("count(//ITEM)");
413
                StringWriter sw2 = new StringWriter();
414
                Serializer destination2 = processor.NewSerializer();
415
                destination2.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
416
                destination2.SetOutputWriter(sw2);
417
                XQueryEvaluator eval2 = exp.Load();
418
                eval2.ContextItem = doc;
419
                eval2.Run(destination2);
420
                Assert.True(sw2.ToString().Equals("0"), "omits ITEM");
421

    
422
            }
423
            catch (Exception ex)
424
            {
425
                Console.WriteLine(ex.StackTrace);
426
                Assert.Fail(ex.Message);
427
            }
428
        }
429

    
430

    
431
        [Test]
432
        public void TestSvg11Dtd()
433
        {
434
            // Test that the SVG 1.1 DTD can be retrieved from the local cache
435
            try
436
            {
437
                Processor proc = new Processor(false);
438
                proc.SetProperty("http://saxon.sf.net/feature/timing", "true");
439
                DocumentBuilder b = proc.NewDocumentBuilder();
440
                b.DtdValidation = (true);
441
                StringReader sr = new StringReader(
442
                        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
443
                            "<!-- Generated by graphviz version 2.28.0 (20110901.0847)\n" +
444
                            " --><!-- Title: g Pages: 1 --><!DOCTYPE svg\n" +
445
                            "  PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n" +
446
                            "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n" +
447
                            "     width=\"206pt\"\n" +
448
                            "     height=\"98pt\"\n" +
449
                            "     viewBox=\"0.00pt 0.00pt 206.00pt 98.00pt\"\n" +
450
                            "     preserveAspectRatio=\"xMidYMid meet\"\n" +
451
                            "     zoomAndPan=\"magnify\"\n" +
452
                            "     version=\"1.1\"\n" +
453
                            "     contentScriptType=\"application/ecmascript\"\n" +
454
                            "     contentStyleType=\"text/css\">\n" +
455
                            "   <g id=\"graph1\" class=\"graph\" transform=\"scale(1 1) rotate(0) translate(4 94)\">\n" +
456
                            "      <title>g</title>\n" +
457
                            "      <polygon fill=\"white\" stroke=\"white\" points=\"-4,5 -4,-94 203,-94 203,5 -4,5\"/>\n" +
458
                            "      <!-- d7e7880 --><g id=\"node2\" class=\"node\">\n" +
459
                            "         <title>d7e7880</title>\n" +
460
                            "         <polygon fill=\"none\" stroke=\"black\" points=\"54,-63 0,-63 0,-27 54,-27 54,-63\"/>\n" +
461
                            "         <text text-anchor=\"middle\" x=\"27\" y=\"-40.4\" font-family=\"Times,serif\"\n" +
462
                            "               font-size=\"14.00\">A</text>\n" +
463
                            "      </g>\n" +
464
                            "   </g>\n" +
465
                            "</svg>");
466
                //StreamSource ss = new StreamSource(sr, "http://www.saxonica.com/notthere");
467
                var stream = new MemoryStream();
468
                var writer = new StreamWriter(stream);
469
                writer.Write(sr);
470
                writer.Flush();
471
                stream.Position = 0;
472
                b.BaseUri = new Uri("http://www.saxonica.com/notthere");
473
                b.Build(stream);
474
                Assert.True(true, "svg11Dtd successful");
475
            }
476
            catch (Exception sae)
477
            {
478
                Assert.Fail(sae.Message);
479
            }
480
        }
481

    
482
        [Test]
483
        public void TestSvg10Dtd()
484
        {
485
            // Test that the SVG 1.0 DTD can be retrieved from the local cache
486
            try
487
            {
488
                Processor proc = new Processor(false);
489
                proc.SetProperty("http://saxon.sf.net/feature/timing", "true");
490
                DocumentBuilder b = proc.NewDocumentBuilder();
491
                b.DtdValidation = true;
492
                StringReader sr = new StringReader(
493
                        "<?xml version='1.0' encoding='UTF-8' ?>"+
494
"<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.0//EN' 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd'>" + Environment.NewLine +
495
"<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='206pt'" + Environment.NewLine +
496
 "   height ='98pt' viewBox='0.00pt 0.00pt 206.00pt 98.00pt' preserveAspectRatio='xMidYMid meet'" + Environment.NewLine +
497
  "  zoomAndPan ='magnify' version='1.0' contentScriptType='application/ecmascript'" + Environment.NewLine +
498
  "  contentStyleType ='text/css'>" + Environment.NewLine +
499
" <g id='graph1' class='graph' transform='scale(1 1) rotate(0) translate(4 94)'>" + Environment.NewLine +
500
 "       <title>g</title>" + Environment.NewLine +
501
 "       <polygon fill='white' stroke='white' points='-4,5 -4,-94 203,-94 203,5 -4,5'/>" + Environment.NewLine +
502
 "       <!-- d7e7880 -->" + Environment.NewLine +
503
 "       <g id='node2' class='node'>" + Environment.NewLine +
504
 "           <title>d7e7880</title>" + Environment.NewLine +
505
 "           <polygon fill='none' stroke='black' points='54,-63 0,-63 0,-27 54,-27 54,-63'/>" + Environment.NewLine +
506
 "           <text text-anchor='middle' x='27' y='-40.4' font-family='Times,serif' font-size='14.00'" + Environment.NewLine +
507
 "               >A</text>" + Environment.NewLine +
508
 "       </g>" + Environment.NewLine +
509
 "   </g>" + Environment.NewLine +
510
"</svg>");
511
                //StreamSource ss = new StreamSource(sr, "http://www.saxonica.com/notthere");
512
                var stream = new MemoryStream();
513
                var writer = new StreamWriter(stream);
514
                writer.Write(sr);
515
                writer.Flush();
516
                stream.Position = 0;
517
                b.BaseUri = new Uri("http://www.saxonica.com/notthere");
518
                b.Build(stream);
519
                Assert.True(true, "svg10Dtd successful");
520

    
521
            }
522
            catch (Exception sae)
523
            {
524
                Assert.Fail(sae.Message);
525
            }
526
        }
527

    
528

    
529
        [Test]
530
        public void TestWhitespacePolicyUntyped()
531
        {
532
            try
533
            {
534
                Processor proc = new Processor(false);
535
                StringReader sr = new StringReader("<doc> </doc>");
536
                DocumentBuilder builder = proc.NewDocumentBuilder();
537
                builder.BaseUri = new Uri("http://www.example.com");
538
                //SAXSource source = new SAXSource(new InputSource(sr));
539
                builder.WhitespacePolicy = WhitespacePolicy.StripAll;
540
                String s = builder.Build(sr).ToString();
541
                Assert.True(s.Contains("<doc/>"));
542

    
543
                sr = new StringReader("<doc> </doc>");
544
                //source = new SAXSource(new InputSource(sr));
545
                builder.WhitespacePolicy = WhitespacePolicy.PreserveAll;
546
                s = builder.Build(sr).ToString();
547
                Assert.True(s.Contains("<doc> </doc"));
548

    
549
                sr = new StringReader("<doc> </doc>");
550
                //source = new SAXSource(new InputSource(sr));
551
                builder.WhitespacePolicy = WhitespacePolicy.StripIgnorable;
552
                s = builder.Build(sr).ToString();
553
                Assert.True(s.Contains("<doc> </doc"));
554

    
555
            }
556
            catch (Exception e)
557
            {
558
                Assert.Fail(e.Message);
559
            }
560
        }
561

    
562
        [Test]
563
        public void TestWhitespacePolicySchemaTyped() {
564
            String s;
565
            s = buildWithWhitespacePolicyTyped(WhitespacePolicy.StripIgnorable);
566
            Assert.True(s.Contains("<BOOKS><ITEM"));
567
            s = buildWithWhitespacePolicyTyped(WhitespacePolicy.PreserveAll);
568
            Assert.True(s.StartsWith("rejected"));
569
            s = buildWithWhitespacePolicyTyped(WhitespacePolicy.StripAll);
570
            Assert.True(s.StartsWith("rejected"));
571

    
572
        }
573

    
574
        private String buildWithWhitespacePolicyTyped(WhitespacePolicy policy)
575
        {
576
            try
577
            {
578
                Processor proc = new Processor(true);
579

    
580
                SchemaManager mgr = proc.SchemaManager;
581
                mgr.Compile(new XmlTextReader(ConfigTest.DATA_DIR + "books.xsd"));
582
                SchemaValidator v = mgr.NewSchemaValidator();
583

    
584
                Serializer serializer = proc.NewSerializer();
585
                serializer.SetOutputProperty(Serializer.METHOD, "xml");
586
                serializer.SetOutputProperty(Serializer.INDENT, "no");
587
                StringWriter sw = new StringWriter();
588

    
589
                DocumentBuilder builder = proc.NewDocumentBuilder();
590
                builder.SchemaValidator = v;
591
                    builder.WhitespacePolicy = policy;
592
                XdmNode doc = builder.Build(new XmlTextReader(ConfigTest.DATA_DIR + "books.xml"));
593
                serializer.SetOutputWriter(sw);
594
                serializer.SerializeXdmValue(doc);
595
                return sw.ToString();
596

    
597
            }
598
            catch (Exception e)
599
            {
600
                return "rejected: " + e.Message;
601
            }
602
        }
603

    
604
        [Test]
605
        public void TestWhitespacePolicyWithDTDValidation()
606
        {
607
            String s;
608
            s = useDTDIgnorableWhitespace(WhitespacePolicy.StripAll);
609
            Assert.True(s.StartsWith("rejected"));
610
            s = useDTDIgnorableWhitespace(WhitespacePolicy.StripIgnorable);
611
            Assert.True(s.Contains("<a><b/><c> </c></a>"));
612
            s = useDTDIgnorableWhitespace(WhitespacePolicy.PreserveAll);
613
            Assert.True(s.StartsWith("rejected"));
614
        }
615

    
616
        private String useDTDIgnorableWhitespace(WhitespacePolicy policy)
617
        {
618
            String validXML = "<!DOCTYPE a [<!ELEMENT a ((b|c)*)><!ELEMENT b EMPTY><!ELEMENT c (#PCDATA)>]><a> <b/> <c> </c> </a>";
619
            Processor proc = new Processor(false);
620
            DocumentBuilder builder = new Processor(false).NewDocumentBuilder();
621
            builder.BaseUri = new Uri("http://example.com");
622
            builder.WhitespacePolicy = policy;
623
            builder.DtdValidation = true;
624

    
625
            StringReader sr = new StringReader(validXML);
626
      
627
            try
628
            {
629
                XdmNode d = builder.Build(sr);
630

    
631
                Serializer serializer = proc.NewSerializer();
632
                serializer.SetOutputProperty(Serializer.METHOD, "xml");
633
                serializer.SetOutputProperty(Serializer.INDENT, "no");
634
                StringWriter sw = new StringWriter();
635
                serializer.SetOutputWriter(sw);
636
                serializer.SerializeXdmValue(d);
637
                return sw.ToString();
638
            }
639
            catch (Exception e)
640
            {
641
                return "rejected: " + e.Message;
642
            }
643

    
644

    
645
        }
646

    
647
        internal static bool LocalNameEquals(QName value) {
648

    
649
            return value.LocalName.Equals("doc") || value.LocalName.Equals("i"); ;
650
        }
651

    
652
        [Test]
653
        public void TestCustomWhitespacePolicy()
654
        {
655
            try
656
            {
657
                Processor proc = new Processor(false);
658
                DocumentBuilder builder = proc.NewDocumentBuilder();
659
                builder.BaseUri = new Uri("http://example.com");
660
                builder.WhitespacePolicy = WhitespacePolicy.StripAll;
661
                StringReader xml = new StringReader("<doc><b> </b> <i> </i> </doc>");
662
                builder.WhitespacePolicy = WhitespacePolicy.MakeCustomPolicy(LocalNameEquals);
663

    
664

    
665
                XdmNode node = builder.Build(xml);
666

    
667

    
668

    
669
                Serializer ss = proc.NewSerializer();
670
                ss.SetOutputProperty(Serializer.METHOD, "xml");
671
                ss.SetOutputProperty(Serializer.INDENT, "no");
672
                StringWriter writer = new StringWriter();
673
                ss.SetOutputWriter(writer);
674
                ss.SerializeXdmValue(node);
675
                Assert.True(writer.ToString().Contains("<doc><b> </b><i/></doc>"));
676

    
677
            }
678
            catch (Exception ex)
679
            {
680
                Assert.Fail(ex.Message);
681
            }
682
        }
683

    
684
        [Test]
685
        public void TestProcInstructions()
686
        {
687
            try
688
            {
689
                var doc = new XmlDocument();
690
                var pi = doc.CreateProcessingInstruction("foo", "bar");
691
                var builder = new Saxon.Api.Processor().NewDocumentBuilder();
692
                var xdmNode = builder.Build(pi);
693
                Console.WriteLine(xdmNode.NodeKind);
694
                IEnumerator enumer = xdmNode.EnumerateAxis(XdmAxis.Descendant);
695
                enumer.MoveNext();
696
                while (enumer.Current != null)
697
                {
698
                    XdmNode child = (XdmNode)enumer.Current;
699
                    enumer.MoveNext();
700

    
701
                    if (child.NodeKind == XmlNodeType.ProcessingInstruction)
702
                    {
703
                        Assert.True(true, "Expect processingInstruction");
704
                        return;
705
                    }
706
                }
707
                // Assert.True(child.NodeKind == XmlNodeType.ProcessingInstruction, "Expect processingInstruction");
708
                Assert.Fail("Failed");
709
            }
710
            catch (Exception ex)
711
            {
712
                Assert.Fail(ex.Message);
713
            }
714
        }
715

    
716
        [Test]
717
        public void TestAttribute()
718
        {
719
            try
720
            {
721
                var doc = new XmlDocument();
722
                var elem = doc.CreateElement("element1");
723
                var attr = doc.CreateAttribute("foo");
724
                attr.Value = "bar";
725
                
726
                elem.SetAttributeNode(attr);
727
                var builder = new Processor().NewDocumentBuilder();
728

    
729
                XdmNode xdmNode = builder.Build(elem);
730
                Console.WriteLine(xdmNode.NodeKind);
731
                IEnumerator enumer = xdmNode.EnumerateAxis(XdmAxis.Descendant);
732
                enumer.MoveNext();
733
                while (enumer.Current != null)
734
                {
735
                    XdmNode child = (XdmNode)enumer.Current;
736
                    enumer.MoveNext();
737

    
738
                    if (child.NodeKind == XmlNodeType.Element)
739
                    {
740
                        if(child.GetAttributeValue(new QName("foo")).Equals("bar"))
741
                        Assert.True(true, "Expect Attribute");
742
                        return;
743
                    }
744
                }
745
                // Assert.True(child.NodeKind == XmlNodeType.ProcessingInstruction, "Expect processingInstruction");
746
                Assert.Fail("Failed");
747
            }
748
            catch (Exception ex)
749
            {
750
                Assert.Fail(ex.Message);
751
            }
752
        }
753

    
754

    
755
        public XsltExecutable GetExecutable(string stylesheetPath)
756
        {
757
            using (FileStream s = new FileStream(stylesheetPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
758
            {
759
                var processor = new Processor();
760
                var compiler = processor.NewXsltCompiler();
761
                compiler.BaseUri = new Uri(stylesheetPath);
762
                var executable = compiler.Compile(s);
763
                return executable;
764
            }
765
        }
766

    
767
        public class MyStream : MemoryStream {
768

    
769
            public override void Close() {
770
                base.Close();
771
            }
772
        }
773

    
774

    
775
        [Test]
776
        public void GetXslt2FO()
777
        {
778
            try {
779
                XmlDocument xml = new XmlDocument();
780
                XmlNode rootNode = xml.CreateElement("users");
781
                xml.AppendChild(rootNode);
782

    
783
                XmlNode userNode = xml.CreateElement("user");
784
                XmlAttribute attribute = xml.CreateAttribute("age");
785
                attribute.Value = "42";
786
                userNode.Attributes.Append(attribute);
787
                userNode.InnerText = "John Doe";
788
                rootNode.AppendChild(userNode);
789

    
790
               
791
                Dictionary<string, string> args = new Dictionary<string, string>();
792

    
793
                string xsltFilePath = ConfigTest.DATA_DIR + "main3.xsl";
794
                // var xsltStep1 = c.Compile(new Uri(ConfigTest.DATA_DIR + "echo_given_sourcefile.xsl"));
795
                // var xsltStep2 = c.Compile(new Uri(ConfigTest.DATA_DIR + "print_elements.xsl"));
796

    
797
                // Compile stylesheet
798
                var executable = GetExecutable(xsltFilePath);
799
                var declaredArgs = executable.GetGlobalParameters();
800

    
801
                // Do transformation to a destination
802
                var destination = new DomDestination();
803
                using (var inputStream = new MyStream())
804
                {
805
                    xml.Save(inputStream);
806
                    inputStream.Position = 0;
807
                    var transformer = executable.Load();
808
                    FileInfo stylesheetFileInfo = new FileInfo(xsltFilePath);
809
                    transformer.SetInputStream(inputStream, new Uri(stylesheetFileInfo.DirectoryName));
810
                    foreach (var arg in args)
811
                    {
812
                        var matchingArgDeclaration = declaredArgs.FirstOrDefault(a => a.Key.LocalName.ToLower() == arg.Key.ToLower());
813
                        if (matchingArgDeclaration.Key == null)
814
                        {
815
                            transformer.SetParameter(new QName(arg.Key), new XdmAtomicValue(arg.Value));
816
                        }
817
                        else
818
                        {
819
                            // try to load up the specific parameter type
820
                            // list is based on http://www.saxonica.com/documentation/#!dotnetdoc/Saxon.Api/XdmAtomicValue
821
                            XdmItemType argType = matchingArgDeclaration.Value.GetDeclaredItemType();
822
                            var argTypeName = "";
823
                            if (argType != null &&
824
                                argType is XdmAtomicType)
825
                                argTypeName = ((XdmAtomicType)argType).Name.LocalName;
826
                            switch (argTypeName.ToLower())
827
                            {
828
                                case "boolean":
829
                                    transformer.SetParameter(new QName(arg.Key), new XdmAtomicValue(Convert.ToBoolean(arg.Value)));
830
                                    break;
831

    
832
                                case "integer":
833
                                    transformer.SetParameter(new QName(arg.Key), new XdmAtomicValue(Convert.ToInt32(arg.Value)));
834
                                    break;
835

    
836
                                case "decimal":
837
                                    transformer.SetParameter(new QName(arg.Key), new XdmAtomicValue(Convert.ToDecimal(arg.Value)));
838
                                    break;
839

    
840
                                case "float":
841
                                    transformer.SetParameter(new QName(arg.Key), new XdmAtomicValue(Convert.ToSingle(arg.Value)));
842
                                    break;
843

    
844
                                case "double":
845
                                    transformer.SetParameter(new QName(arg.Key), new XdmAtomicValue(Convert.ToDouble(arg.Value)));
846
                                    break;
847

    
848
                                case "anyuri":
849
                                    transformer.SetParameter(new QName(arg.Key), new XdmAtomicValue(new Uri(arg.Value)));
850
                                    break;
851

    
852
                                case "qname":
853
                                    transformer.SetParameter(new QName(arg.Key), new XdmAtomicValue(new QName(arg.Value)));
854
                                    break;
855

    
856
                                default:
857
                                    transformer.SetParameter(new QName(arg.Key), new XdmAtomicValue(((arg.Value))));
858
                                    break;
859
                            }
860
                        }
861
                    }
862

    
863
                    transformer.Run(destination);
864
                }
865
                Console.WriteLine(destination.XmlDocument.OuterXml);
866
                Assert.True(destination.XmlDocument.OuterXml is string);
867

    
868
            } catch (Exception ex) {
869
                Console.WriteLine(ex.StackTrace);
870
                Assert.Fail(ex.Message);
871
            }
872
        }
873
    }
874
}
875

    
876

    
(9-9/19)