Exemplo n.º 1
0
    /**
     * This shows how to set a parameter for use by the stylesheet. Use
     * two transformers to show that different parameters may be set
     * on different transformers.
     */
    public static void ExampleParam(String sourceUri, String xsltUri)
    {
        // Create a Processor instance.
        Processor processor = new Processor();

        // Load the source document
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));

        // Compile the stylesheet
        XsltExecutable exec = processor.NewXsltCompiler().Compile(new Uri(xsltUri));

        // Create two transformers with different parameters
        XsltTransformer transformer1 = exec.Load();
        XsltTransformer transformer2 = exec.Load();

        transformer1.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("hello to you!"));
        transformer2.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("goodbye to you!"));

        // Now run them both
        transformer1.InitialContextNode = input;
        XdmDestination results1 = new XdmDestination();

        transformer1.Run(results1);

        transformer2.InitialContextNode = input;
        XdmDestination results2 = new XdmDestination();

        transformer2.Run(results2);

        Console.WriteLine("1: " + results1.XdmNode.StringValue);
        Console.WriteLine("2: " + results2.XdmNode.StringValue);
    }
Exemplo n.º 2
0
    /**
     * Perform a transformation using a compiled stylesheet (a Templates object)
     */
    public static void ExampleUseTemplatesObj(
        String sourceUri1, String sourceUri2, String xsltUri)
    {
        // Create a Processor instance.
        Processor processor = new Processor();

        // Create a compiled stylesheet
        XsltExecutable templates = processor.NewXsltCompiler().Compile(new Uri(xsltUri));

        // Note: we could actually use the same XSltTransformer in this case.
        // But in principle, the two transformations could be done in parallel in separate threads.

        // Do the first transformation
        Console.WriteLine("\n\n----- transform of " + sourceUri1 + " -----");
        XsltTransformer transformer1 = templates.Load();

        transformer1.InitialContextNode = processor.NewDocumentBuilder().Build(new Uri(sourceUri1));
        transformer1.Run(new Serializer());     // default destination is Console.Out

        // Do the second transformation
        Console.WriteLine("\n\n----- transform of " + sourceUri2 + " -----");
        XsltTransformer transformer2 = templates.Load();

        transformer2.InitialContextNode = processor.NewDocumentBuilder().Build(new Uri(sourceUri2));
        transformer2.Run(new Serializer());     // default destination is Console.Out
    }
Exemplo n.º 3
0
        ///<summary>
        ///Performs a Saxon transformation.
        /// </summary>
        ///
        public override Stream Transform(Stream source, Stream xsl)
        {
            MemoryStream result = new MemoryStream();

            Uri uri = new Uri("file://C:/");

            //set XSLT stylesheet
            Processor    p = new Processor();
            XsltCompiler c = p.NewXsltCompiler();

            c.BaseUri = uri;
            XsltExecutable  e = c.Compile(xsl);
            XsltTransformer t = e.Load();

            //set output

            var destination = new Serializer();

            destination.SetOutputStream(result);
            t.SetInputStream(source, uri);
            t.Run(destination);

            result.Position = 0;
            result.Flush();
            return(result);
        }
Exemplo n.º 4
0
        public static string TransformSAXON(string documentPath, string xsltPath, bool schemaAware)
        {
            Processor    processor    = new Processor();
            XsltCompiler xsltCompiler = processor.NewXsltCompiler();

            xsltCompiler.Processor.SetProperty(FeatureKeys.GENERATE_BYTE_CODE, "false");
            XsltExecutable  xsltExecutable  = xsltCompiler.Compile(new Uri("file://" + xsltPath));
            XsltTransformer xsltTransformer = xsltExecutable.Load();

            if (schemaAware
                //!string.IsNullOrEmpty(xsdPath)
                )
            {
                xsltTransformer.SchemaValidationMode = SchemaValidationMode.Strict;
            }

            using (FileStream fileStream = File.OpenRead(documentPath))
            {
                xsltTransformer.SetInputStream(fileStream, new Uri(@"file://" + documentPath));
                XdmDestination destination = new XdmDestination();
                xsltTransformer.Run(destination);
                StringBuilder outputBuilder = new StringBuilder();
                outputBuilder.Append(destination.XdmNode.OuterXml);
                return(outputBuilder.ToString());
            }
        }
Exemplo n.º 5
0
        private string Transform(string stylesheetContent, string xmlPath, bool addErrorsPhase = false)
        {
            FileInfo xmlInfo    = new FileInfo(xmlPath);
            XdmNode  stylesheet = builder.Build(new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(stylesheetContent))));

            XsltCompiler   compiler = processor.NewXsltCompiler();
            XsltExecutable exec     = compiler.Compile(stylesheet);

            XsltTransformer transformer = exec.Load();
            DomDestination  dest        = new DomDestination();

            using (var inputStream = xmlInfo.OpenRead())
            {
                if (addErrorsPhase)
                {
                    transformer.SetParameter(new QName("phase"), XdmValue.MakeValue("errors"));
                }

                transformer.SetInputStream(inputStream, new Uri(xmlInfo.DirectoryName));
                transformer.Run(dest);
            }

            using (StringWriter sw = new StringWriter())
            {
                if (dest.XmlDocument == null)
                {
                    throw new Exception("Failed to execute Schematron validation. The SCH file selected may not be the ISO version of Schematron.");
                }

                dest.XmlDocument.Save(sw);
                return(sw.ToString());
            }
        }
Exemplo n.º 6
0
        public static string TransformXMLToHTML(Stream input, Stream transformXsl, Stream output)
        {
            try
            {
                Processor      xsltProcessor  = new Processor();
                XsltCompiler   xsltCompiler   = xsltProcessor.NewXsltCompiler();
                XsltExecutable xsltExecutable = xsltCompiler.Compile(transformXsl);

                var           xsltTransformer = xsltExecutable.Load();
                XmlTextReader modelFileXML    = new XmlTextReader(input);
                XdmNode       xdmNode         = xsltProcessor.NewDocumentBuilder().Build(modelFileXML);
                xsltTransformer.InitialContextNode = xdmNode;

                Serializer serializer = xsltProcessor.NewSerializer();
                serializer.SetOutputStream(output);

                xsltTransformer.Run(serializer);
                return("");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\r\n" + e.StackTrace);
                return(string.Empty);
            }
        }
Exemplo n.º 7
0
    /**
     * Show the that a transformer can be reused, and show resetting
     * a parameter on the transformer.
     */
    public static void ExampleTransformerReuse(String sourceUri, String xsltUri)
    {
        // Create a Processor instance.
        Processor processor = new Processor();

        // Load the source document
        XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));

        // Compile the stylesheet
        XsltExecutable exec = processor.NewXsltCompiler().Compile(new Uri(xsltUri));

        // Create a transformer
        XsltTransformer transformer = exec.Load();

        // Run it once
        transformer.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("hello to you!"));
        transformer.InitialContextNode = input;
        XdmDestination results = new XdmDestination();

        transformer.Run(results);
        Console.WriteLine("1: " + results.XdmNode.StringValue);

        // Run it again
        transformer.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("hello to me!"));
        transformer.InitialContextNode = input;
        results.Reset();
        transformer.Run(results);
        Console.WriteLine("2: " + results.XdmNode.StringValue);
    }
Exemplo n.º 8
0
        private String compareDocs(XdmNode doc1, XdmNode doc2)
        {
            try {
                XsltTransformer t = xmlComparer.Load();
                t.InitialTemplate = new QName("", "compare");
                t.SetParameter(new QName("", "actual"), doc1);
                t.SetParameter(new QName("", "gold"), doc2);
                t.SetParameter(new QName("", "debug"), new XdmAtomicValue(debug));

                StringWriter sw = new StringWriter();
                Serializer   sr = new Serializer();
                sr.SetOutputWriter(sw);

                t.Run(sr);
                String result = sw.ToString();
                if (result.StartsWith("true"))
                {
                    return("OK");
                }
                else
                {
                    return("XML comparison - not equal");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("***" + e.Message);
                return("XML comparison failure: " + e.Message);
            }
        }
        private string ProcessXslt(string result, string xslt)
        {
            XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(result));
            string   cleanXmlDocument     = xmlDocumentWithoutNs.ToString();

            XsltExecutable xsltExecutable = GetXsltExecutable(xslt);

            byte[]          xmlByteArray = System.Text.Encoding.UTF8.GetBytes(cleanXmlDocument);
            var             inputStream  = new MemoryStream(xmlByteArray);
            XsltTransformer transformer  = xsltExecutable.Load();

            // Saxon requires to set an Uri for the stream; otherwise setting the input stream fails
            transformer.SetInputStream(inputStream, new Uri("http://localhost"));

            // run the transformation and save the result to string
            Serializer serializer = new Processor().NewSerializer();

            using (var memoryStream = new MemoryStream())
            {
                serializer.SetOutputStream(memoryStream);
                transformer.Run(serializer);
                memoryStream.Position = 0;
                using (var streamReader = new StreamReader(memoryStream))
                {
                    result = streamReader.ReadToEnd();
                }
            }

            return(result.Contains(NoMatchString) ? null : result);
        }
Exemplo n.º 10
0
    private bool compareXML(String actual, String gold)
    {
        try {
            if (xmlComparer == null)
            {
                xmlComparer = processor.NewXsltCompiler().Compile(new Uri(testSuiteDir + "/SaxonResults.net/compare.xsl"));
            }
            XdmNode         doc1 = processor.NewDocumentBuilder().Build(new Uri(actual));
            XdmNode         doc2 = processor.NewDocumentBuilder().Build(new Uri(gold));
            XsltTransformer t    = xmlComparer.Load();
            t.InitialTemplate = new QName("", "compare");
            t.SetParameter(new QName("", "actual"), doc1);
            t.SetParameter(new QName("", "gold"), doc2);

            StringWriter sw = new StringWriter();
            Serializer   sr = new Serializer();
            sr.SetOutputWriter(sw);

            t.Run(sr);
            String result = sw.ToString();
            return(result.StartsWith("true"));
        } catch (Exception e) {
            Console.WriteLine("***" + e.Message);
            return(false);
        }
    }
Exemplo n.º 11
0
        public override void TreeToTreeTransform()
        {
            XsltTransformer transformer = stylesheet.Load();

            if (sourceDocument != null)
            {
                transformer.InitialContextNode = sourceDocument;
            }
            else
            {
                transformer.InitialTemplate = new QName("main");
            }
            XdmDestination destination = new XdmDestination();

            transformer.Run(destination);
            resultDocument = destination.XdmNode;
        }
Exemplo n.º 12
0
        public override void TreeToTreeTransform()
        {
            XsltTransformer transformer = stylesheet.Load();

            processor.SetProperty(net.sf.saxon.lib.FeatureKeys.SCHEMA_VALIDATION_MODE, schemaAware ? "strict" : "strip");
            //transformer.SchemaValidationMode = SchemaValidationMode.Strict;   // not working in 9.5.1.5: see bug 2062
            if (sourceDocument != null)
            {
                transformer.InitialContextNode = sourceDocument;
            }
            else
            {
                transformer.InitialTemplate = new QName("main");
            }
            XdmDestination destination = new XdmDestination();

            transformer.Run(destination);
            resultDocument = destination.XdmNode;
        }
        public ActionResult Upload(IEnumerable <HttpPostedFileBase> fileUpload)
        {
            foreach (var file in fileUpload)
            {
                if (Request.Files.Count > 0)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        var fileName  = Path.GetFileName(file.FileName);
                        var path      = Path.Combine(Server.MapPath("~/Files/"), fileName);
                        var extension = Path.GetExtension(file.FileName); //dosya uzantısını aldım
                        switch (extension)                                // Uzantıya göre texareaya yönlendirdim
                        {
                        case ".xml":
                            ViewBag.mesaj = System.IO.File.ReadAllText(path);

                            localPathXml = path;
                            break;

                        case ".xslt":
                            ViewBag.mesaj2 = System.IO.File.ReadAllText(path);

                            localPathXslt = path;
                            break;
                        }
                        SaveExtension = extension;
                    }
                }
            }
            //Dosyalar upload edildikten sonra Saxon HE ile tranform işlemi yap
            Processor       xsltProcessor   = new Processor();
            DocumentBuilder documentBuilder = xsltProcessor.NewDocumentBuilder();

            documentBuilder.BaseUri = new Uri("file://");
            XdmNode xdmNode = documentBuilder.Build(new StringReader(ViewBag.mesaj));

            XsltCompiler    xsltCompiler    = xsltProcessor.NewXsltCompiler();
            XsltExecutable  xsltExecutable  = xsltCompiler.Compile(new StringReader(ViewBag.mesaj2));
            XsltTransformer xsltTransformer = xsltExecutable.Load();

            xsltTransformer.InitialContextNode = xdmNode;

            using (StringWriter stringWriter = new StringWriter())
            {
                Serializer serializer = new Serializer();
                serializer.SetOutputWriter(stringWriter);
                xsltTransformer.Run(serializer);
                ViewBag.cikti = stringWriter;
            }

            return(View("Index"));
        }
Exemplo n.º 14
0
        //run an XSLT transform.
        //transformFile is the name of the .xsl to run;
        //path is usually tools directory (be sure to include final slash in passed string)
        //takes two paramaters and corresponding values; use empty strings if not needed
        static public XmlDocument performTransformWith2Params(XmlDocument inDOM, string path, string transformFile, string param1Name, string param1Value, string param2Name, string param2Value)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

            // Load the source document, building a tree
            XmlNode node  = inDOM;
            XdmNode input = processor.NewDocumentBuilder().Build(node);

            // Compile the stylesheet
            XsltExecutable exec = processor.NewXsltCompiler().Compile(new XmlTextReader(path.Replace("Program Files", "PROGRA~1") + transformFile));

            // Create a transformer
            XsltTransformer transformer = exec.Load();

            string xdmToolsPath = "file:/" + path.Replace("\\", "/").Replace(" ", "%20");

            // Run it once
            // Set parameters
            transformer.SetParameter(new QName("", "", "include-attributes"), new XdmAtomicValue(false));
            //following may be needed if xslt itself needs to find other files
            transformer.SetParameter(new QName("", "", "localBaseUri"), new XdmAtomicValue(xdmToolsPath.Replace("Program%20Files", "PROGRA~1")));
            //optionally add another parameter
            if (!String.IsNullOrEmpty(param1Name))
            {
                transformer.SetParameter(new QName("", "", param1Name), new XdmAtomicValue(param1Value));
            }
            //and another param
            if (!String.IsNullOrEmpty(param2Name))
            {
                transformer.SetParameter(new QName("", "", param2Name), new XdmAtomicValue(param2Value));
            }

            transformer.InitialContextNode = input;
            XdmDestination results = new XdmDestination();

            transformer.Run(results);

            XmlDocument resultXmlDoc = new XmlDocument();

            resultXmlDoc.LoadXml(results.XdmNode.OuterXml);
            XmlDeclaration declaration = resultXmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);

            resultXmlDoc.PrependChild(declaration);

            // return the result
            return(resultXmlDoc);
        }
Exemplo n.º 15
0
 private String canonizeXhtml(Processor p, String input)
 {
     try {
         XsltExecutable  canonizer = getXhtmlCanonizer(p);
         XsltTransformer t         = canonizer.Load();
         StringWriter    sw        = new StringWriter();
         Serializer      r         = new Serializer();
         r.SetOutputWriter(sw);
         t.InitialContextNode = p.NewDocumentBuilder().Build(
             new FileStream(input, FileMode.Open));
         t.Run(r);
         return(sw.ToString());
     } catch (Exception err) {
         Console.WriteLine("*** Failed to compile or run XHTML canonicalizer stylesheet: " + err.ToString());
     }
     return("");
 }
        public string InvoiceTransform(string code, string code2)
        {
            string invoiceHtml = String.Empty;

            if (code == "" || code2 == "")
            {
                Response.Write("<script lang='JavaScript'>alert('Dosyaları Yüklemeden Kaydetme İşlemi Gerçekleşmez');</script>");
            }
            else
            {
                //textarealardaki değişikliklerini hafızaya kaydet
                MemoryStream Xml = new MemoryStream(Encoding.UTF8.GetBytes(code));
                Xml.Write(System.Text.Encoding.UTF8.GetBytes(code), 0, code.Length);
                ViewBag.mesaj = code;


                MemoryStream Xslt = new MemoryStream(Encoding.UTF8.GetBytes(code2));
                Xslt.Write(System.Text.Encoding.UTF8.GetBytes(code2), 0, code2.Length);
                ViewBag.mesaj2 = code2;

                localXmlString  = ViewBag.mesaj;
                localXsltString = ViewBag.mesaj2;


                Processor       xsltProcessor   = new Processor();
                DocumentBuilder documentBuilder = xsltProcessor.NewDocumentBuilder();
                documentBuilder.BaseUri = new Uri("file://");
                XdmNode xdmNode = documentBuilder.Build(new StringReader(code));

                XsltCompiler    xsltCompiler    = xsltProcessor.NewXsltCompiler();
                XsltExecutable  xsltExecutable  = xsltCompiler.Compile(new StringReader(code2));
                XsltTransformer xsltTransformer = xsltExecutable.Load();
                xsltTransformer.InitialContextNode = xdmNode;

                using (StringWriter stringWriter = new StringWriter())
                {
                    Serializer serializer = new Serializer();
                    serializer.SetOutputWriter(stringWriter);
                    xsltTransformer.Run(serializer);
                    ViewBag.cikti = stringWriter;
                    invoiceHtml   = stringWriter.ToString();
                }
            }
            return(invoiceHtml);
        }
Exemplo n.º 17
0
        public XmlDocument Run(XNode xDocument, string baseOutputUri = null, params KeyValuePair <string, object>[] arguments)
        {
            // Load the source document from an XMLReader.
            var reader = xDocument.CreateReader();

            // Load execuable.
            var transformer = _executable.Load();

            // Set the root node of the source document to be the initial context node
            transformer.InitialContextNode = _builder.Build(reader);

            // Set where to output xsl:result-document constructs.
            if (baseOutputUri != null)
            {
                transformer.BaseOutputUri = new Uri(baseOutputUri);
            }

            // Set parameters.
            this.SetParams(ref transformer, arguments);

            // The transformation destination variable.
            var destination = new DomDestination();

            // Errors will be reported by the exception handling.
            transformer.Implementation.setErrorListener(new TransformerErrorListener());

            // Output the transform to the above variable.
            var listener = new DynamicErrorListener();

            try
            {
                transformer.Implementation.setErrorListener(listener);
                transformer.Run(destination);
            }
            catch (DynamicError)
            {
                this.ReportCompilerErrors(listener);
            }

            // Clear any set parameters.
            transformer.Reset();

            return(destination.XmlDocument);
        }
Exemplo n.º 18
0
        public static void Transform(string styleSheet, string inputFile, string outputFile)
        {
            Processor processor     = new Processor();
            var       uriInput      = new System.Uri(inputFile);
            var       uriStyleSheet = new System.Uri(styleSheet);

            XdmNode         inputXdmNode    = processor.NewDocumentBuilder().Build(uriInput);
            XsltCompiler    xsltCompiler    = processor.NewXsltCompiler();
            XsltExecutable  xsltExecutable  = xsltCompiler.Compile(uriStyleSheet);
            XsltTransformer xsltTransformer = xsltExecutable.Load();

            xsltTransformer.InitialContextNode = inputXdmNode;

            Serializer   serializer   = processor.NewSerializer();
            StreamWriter streamWriter = new StreamWriter(outputFile);

            serializer.SetOutputWriter(streamWriter);
            xsltTransformer.Run(serializer);
            streamWriter.Close();
        }
Exemplo n.º 19
0
        protected override void runTestCase(XdmNode testCase, XPathCompiler xpath)
        {
            TestOutcome outcome     = new TestOutcome(this);
            string      testName    = testCase.GetAttributeValue(new QName("name"));
            string      testSetName = testCase.Parent.GetAttributeValue(new QName("name"));

            ////
            if (testName.Equals("type-0174"))
            {
                int num = 0;
                System.Console.WriteLine("Test driver" + num);
            }

            ///
            if (exceptionsMap.ContainsKey(testName))
            {
                notrun++;
                resultsDoc.writeTestcaseElement(testName, "notRun", exceptionsMap[testName].GetAttributeValue(new QName("reason")));
                return;
            }

            if (exceptionsMap.ContainsKey(testName) || isSlow(testName))
            {
                notrun++;
                resultsDoc.writeTestcaseElement(testName, "notRun", "requires excessive resources");
                return;
            }



            XdmValue specAtt = (XdmValue)(xpath.EvaluateSingle("(/test-set/dependencies/spec/@value, ./dependencies/spec/@value)[last()]", testCase));
            string   spec    = specAtt.ToString();

            Environment env = getEnvironment(testCase, xpath);

            if (env == null)
            {
                resultsDoc.writeTestcaseElement(testName, "notRun", "test catalog error");
                return;
            }

            /*if(testName("environment-variable")) {
             *              EnvironmentVariableResolver resolver = new EnvironmentVariableResolver() {
             *          public Set<string> getAvailableEnvironmentVariables() {
             *              Set<string> strings = new HashSet<string>();
             *              strings.add("QTTEST");
             *              strings.add("QTTEST2");
             *              strings.add("QTTESTEMPTY");
             *              return strings;
             *          }
             *
             *          public string getEnvironmentVariable(string name) {
             *              if (name.Equals("QTTEST")) {
             *                  return "42";
             *              } else if (name.Equals("QTTEST2")) {
             *                  return "other";
             *              } else if (name.Equals("QTTESTEMPTY")) {
             *                  return "";
             *              } else {
             *                  return null;
             *              }
             *          }
             *      }; //TODO
             *  } */
            //   env.processor.SetProperty(JFeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER, resolver); //TODO

            XdmNode testInput  = (XdmNode)xpath.EvaluateSingle("test", testCase);
            XdmNode stylesheet = (XdmNode)xpath.EvaluateSingle("stylesheet", testInput);


            foreach (XdmItem dep in xpath.Evaluate("(/test-set/dependencies/*, ./dependencies/*)", testCase))
            {
                if (!dependencyIsSatisfied((XdmNode)dep, env))
                {
                    notrun++;
                    resultsDoc.writeTestcaseElement(testName, "notRun", "dependency not satisfied");
                    return;
                }
            }

            XsltExecutable sheet = env.xsltExecutable;
            //ErrorCollector collector = new ErrorCollector();
            XmlUrlResolver res = new XmlUrlResolver();

            if (stylesheet != null)
            {
                XsltCompiler compiler = env.xsltCompiler;
                Uri          hrefFile = res.ResolveUri(stylesheet.BaseUri, stylesheet.GetAttributeValue(new QName("file")));
                Stream       stream   = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read);
                compiler.BaseUri             = hrefFile;
                compiler.XsltLanguageVersion = (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0");
                try
                {
                    sheet = compiler.Compile(stream);
                } catch (Exception err) {
                    outcome.SetException(err);

                    //outcome.SetErrorsReported(collector.GetErrorCodes);
                }


                //  compiler.setErrorListener(collector);
            }

            if (sheet != null)
            {
                XdmItem contextItem     = env.contextItem;
                QName   initialMode     = getQNameAttribute(xpath, testInput, "initial-mode/@name");
                QName   initialTemplate = getQNameAttribute(xpath, testInput, "initial-template/@name");

                try {
                    XsltTransformer transformer = sheet.Load();

                    //transformer.SetURIResolver(env); //TODO
                    if (env.unparsedTextResolver != null)
                    {
                        transformer.Implementation.setUnparsedTextURIResolver(env.unparsedTextResolver);
                    }
                    if (initialTemplate != null)
                    {
                        transformer.InitialTemplate = initialTemplate;
                    }
                    if (initialMode != null)
                    {
                        transformer.InitialMode = initialMode;
                    }
                    foreach (XdmItem param in xpath.Evaluate("param", testInput))
                    {
                        string   name   = ((XdmNode)param).GetAttributeValue(new QName("name"));
                        string   select = ((XdmNode)param).GetAttributeValue(new QName("select"));
                        XdmValue value  = xpath.Evaluate(select, null);
                        transformer.SetParameter(new QName(name), value);
                    }
                    if (contextItem != null)
                    {
                        transformer.InitialContextNode = (XdmNode)contextItem;
                    }
                    if (env.streamedPath != null)
                    {
                        transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri);
                    }
                    foreach (QName varName in env.params1.Keys)
                    {
                        transformer.SetParameter(varName, env.params1[varName]);
                    }
                    //transformer.setErrorListener(collector);
                    transformer.BaseOutputUri = new Uri(resultsDir + "/results/output.xml");

                    /*transformer.MessageListener = (new MessageListener() {
                     *  public void message(XdmNode content, bool terminate, SourceLocator locator) {
                     *      outcome.addXslMessage(content);
                     *  }
                     * });*/


                    // Run the transformation twice, once for serialized results, once for a tree.
                    // TODO: we could be smarter about this and capture both

                    // run with serialization
                    StringWriter sw         = new StringWriter();
                    Serializer   serializer = env.processor.NewSerializer(sw);
                    transformer.Implementation.setOutputURIResolver(new OutputResolver(driverProc, outcome, true));


                    transformer.Run(serializer);

                    outcome.SetPrincipalSerializedResult(sw.ToString());
                    if (saveResults)
                    {
                        // currently, only save the principal result file
                        saveResultsToFile(sw.ToString(),
                                          resultsDir + "/results/" + testSetName + "/" + testName + ".out");
                    }
                    transformer.MessageListener = new TestOutcome.MessageListener(outcome);

                    // run without serialization
                    if (env.streamedPath != null)
                    {
                        transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri);
                    }
                    XdmDestination destination = new XdmDestination();
                    transformer.Implementation.setOutputURIResolver(
                        new OutputResolver(env.processor, outcome, false));
                    transformer.Run(destination);

                    //transformer. .transform();
                    outcome.SetPrincipalResult(destination.XdmNode);
                    //}
                } catch (Exception err) {
                    outcome.SetException(err);
                    //outcome.SetErrorsReported(collector.getErrorCodes());
                    // err.printStackTrace();
                    // failures++;
                    //resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.Message);
                    //return;
                }
            }
            XdmNode assertion = (XdmNode)xpath.EvaluateSingle("result/*", testCase);

            if (assertion == null)
            {
                failures++;
                resultsDoc.writeTestcaseElement(testName, "fail", "No test assertions found");
                return;
            }
            XPathCompiler assertionXPath = env.processor.NewXPathCompiler();
            //assertionXPath.setLanguageVersion("3.0");
            bool success = outcome.TestAssertion(assertion, outcome.GetPrincipalResultDoc(), assertionXPath, xpath, debug);

            if (success)
            {
                if (outcome.GetWrongErrorMessage() != null)
                {
                    outcome.SetComment(outcome.GetWrongErrorMessage());
                    wrongErrorResults++;
                }
                else
                {
                    successes++;
                }
                resultsDoc.writeTestcaseElement(testName, "pass", outcome.GetComment());
            }
            else
            {
                failures++;
                resultsDoc.writeTestcaseElement(testName, "fail", outcome.GetComment());
            }
        }
Exemplo n.º 20
0
    protected string runXSLT(String testName, String xml, String xsl, QName initialMode,
                             QName initialTemplate, String outfile, Hashtable paramTable, String initialContextPath,
                             bool useAssociated, bool schemaAware,
                             String validationMode, bool recoverRecoverable)
    {
        Serializer sr = new Serializer();

        sr.SetOutputFile(outfile);
        Processor f;

        //if (noCacheTests.contains(testName) || testName.startsWith("schemaas20") ||
        //        testName.startsWith("striptype20") || testName.startsWith("notation20")) {
        // create a custom Processor to avoid schema caching
        //} else {
        if (schemaAware)
        {
            f = schemaAwareProcessor;
        }
        else if (xml11)
        {
            f = processor;
            // Use an Xml 1.1 processor
        }
        else
        {
            f = processor;
        }
        //}

        XdmNode source = null;

        IList        errors   = new ArrayList();
        XsltCompiler compiler = f.NewXsltCompiler();

        compiler.ErrorList = errors;
        XsltExecutable  sheet = null;
        XsltTransformer inst;

        if (useAssociated)
        {
            try {
                source = buildSource(f.NewDocumentBuilder(), xml, validationMode);
            } catch (Exception e) {
                Console.WriteLine("Failed to build source document: " + e.Message);
                return("ErrorBBB");
            }
            try {
                sheet = compiler.CompileAssociatedStylesheet(source);
            } catch (Exception e) {
                Console.WriteLine("Failed to compile stylesheet: " + e.Message);
                if (errors.Count > 0)
                {
                    QName code = ((StaticError)errors[0]).ErrorCode;
                    return(code == null ? "ErrorXXX" : code.LocalName);
                }
                else
                {
                    return("ErrorXXX");
                }
            }
        }
        else
        {
            Stream stream = new FileStream(xsl, FileMode.Open, FileAccess.Read);
            compiler.BaseUri = new Uri(xsl);
            try {
                sheet = compiler.Compile(stream);
            } catch (Exception e) {
                if (errors.Count > 0)
                {
                    return(((StaticError)errors[0]).ErrorCode.LocalName);
                }
                else
                {
                    Console.WriteLine(e.Message);
                    return("ErrorXXX");
                }
            } finally {
                stream.Close();
            }
        }
        if (source == null && xml != null)
        {
            try {
                source = buildSource(f.NewDocumentBuilder(), xml, validationMode);
            } catch (Exception e) {
                Console.WriteLine("Failed to build source document: " + e.Message);
                return("ErrorCCC");
            }
        }
        if (initialContextPath != null)
        {
            XPathCompiler   xc  = f.NewXPathCompiler();
            XPathExecutable exp = xc.Compile(initialContextPath);
            XPathSelector   xpe = exp.Load();
            xpe.ContextItem = source;
            XdmNode node = (XdmNode)xpe.EvaluateSingle();
            source = node;
        }

        inst = sheet.Load();
        if (initialMode != null)
        {
            inst.InitialMode = initialMode;
        }
        if (initialTemplate != null)
        {
            try {
                inst.InitialTemplate = initialTemplate;
            } catch (DynamicError e) {
                QName code = e.ErrorCode;
                if (code != null)
                {
                    return(code.LocalName);
                }
                else
                {
                    return("ErrYYYYY");
                }
            }
        }
        if (paramTable != null)
        {
            foreach (DictionaryEntry de in paramTable)
            {
                inst.SetParameter((QName)de.Key, new XdmAtomicValue(de.Value.ToString()));
            }
        }
        inst.InitialContextNode = source;

        //inst.setURIResolver(factory.getURIResolver());
        //inst.setErrorListener(errorListener);
        //((Controller)inst).setRecoveryPolicy(recoverRecoverable ? Configuration.RECOVER_SILENTLY : Configuration.DO_NOT_RECOVER);
        // To avoid test results being dependent on the date and time (and timezone), set a fixed
        // date and time for the run
        //((Controller)inst).setCurrentDateTime(new DateTimeValue("2005-01-01T12:49:30.5+01:00"));

        try {
            inst.Run(sr);
        } catch (DynamicError e) {
            Console.WriteLine(e.Message);
            QName code = e.ErrorCode;
            if (code != null)
            {
                return(code.LocalName);
            }
            else
            {
                return("ErrYYYYY");
            }
        }
        return(null);    // indicating success
    }
Exemplo n.º 21
0
        public static string TransformXml(string xmlData, string xslData)
        {
            string results = "";

            try
            {
                // Saxon Transformation Start
                Processor       xsltProcessor   = new Processor();
                DocumentBuilder documentBuilder = xsltProcessor.NewDocumentBuilder();
                documentBuilder.BaseUri = new Uri("file://");
                XdmNode      xdmNode      = documentBuilder.Build(new StringReader(xmlData));
                XsltCompiler xsltCompiler = xsltProcessor.NewXsltCompiler();

                XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(xslData));

                XsltTransformer xsltTransformer = xsltExecutable.Load();
                xsltTransformer.InitialContextNode = xdmNode;

                XdmDestination xdmDest = new XdmDestination();
                xsltTransformer.Run(xdmDest);
                // Saxon Transformation End


                // Handle XML Declaration
                string version     = "1.0";
                string encoding    = "UTF-8";
                string standalone  = null;
                string declaration = new XDeclaration(version, encoding, standalone).ToString() + Environment.NewLine;

                try
                {
                    XDocument  xslt = XDocument.Parse(xslData);
                    XNamespace xsl  = "http://www.w3.org/1999/XSL/Transform";
                    XElement   elem = xslt.Root.Element(xsl + "output");

                    if (elem != null)
                    {
                        if (elem.Attribute("version") != null)
                        {
                            version = elem.Attribute("version").Value;
                        }
                        if (elem.Attribute("encoding") != null)
                        {
                            encoding = elem.Attribute("encoding").Value;
                        }
                        if (elem.Attribute("standalone") != null)
                        {
                            standalone = elem.Attribute("standalone").Value;
                        }
                        declaration = new XDeclaration(version, encoding, standalone).ToString() + Environment.NewLine;

                        // Clear Declaration
                        if (elem.Attribute("omit-xml-declaration") != null && elem.Attribute("omit-xml-declaration").Value == "yes")
                        {
                            declaration = "";
                        }
                        if (elem.Attribute("method") != null && elem.Attribute("method").Value != "xml")
                        {
                            declaration = "";
                        }
                    }
                    // Attempt to prevent duplicate declaration
                    if (xdmDest.XdmNode.OuterXml.StartsWith("<?"))
                    {
                        declaration = "";
                    }
                }
                catch
                {
                    // ignore exception
                }
                results = declaration + xdmDest.XdmNode.OuterXml;
            }
            catch (Exception e)
            {
                throw e;
            }
            return(results);
        }
Exemplo n.º 22
0
    /// <summary>
    /// Run the transformation
    /// </summary>
    /// <param name="testName"></param>
    /// <param name="xml"></param>
    /// <param name="xsl"></param>
    /// <param name="initialMode"></param>
    /// <param name="initialTemplate"></param>
    /// <param name="outfile"></param>
    /// <param name="paramTable"></param>
    /// <param name="initialContextPath"></param>
    /// <param name="useAssociated"></param>
    /// <param name="schemaAware"></param>
    /// <param name="validationMode"></param>
    /// <param name="recoverRecoverable"></param>
    /// <returns>Either null, indicating success, or an Exception object with information about the failure</returns>

    protected Exception runXSLT(String testName, String xml, String xsl, QName initialMode,
                                QName initialTemplate, String outfile, Hashtable paramTable, String initialContextPath,
                                bool useAssociated, bool schemaAware,
                                String validationMode, bool recoverRecoverable, bool useXSLT30)
    {
        Serializer sr = new Serializer();

        sr.SetOutputFile(outfile);
        Processor f;

        if (noCacheTests.ContainsKey(testName))
        {
            //create a custom Processor to avoid schema caching
            f = new Processor(true);
        }
        else if (schemaAware)
        {
            f = schemaAwareProcessor;
            if (f == null)
            {
                return(new DynamicError("Saxon-SA not available"));
            }
        }
        else if (xml11)
        {
            f = processor;
            // Use an Xml 1.1 processor
        }
        else
        {
            f = processor;
        }


        XdmNode source = null;

        IList        errors   = new ArrayList();
        XsltCompiler compiler = f.NewXsltCompiler();

        compiler.SchemaAware = schemaAware;
        compiler.ErrorList   = errors;
        if (useXSLT30)
        {
            compiler.XsltLanguageVersion = "3.0";
        }
        XsltExecutable  sheet = null;
        XsltTransformer inst;

        if (useAssociated)
        {
            try
            {
                source = buildSource(f.NewDocumentBuilder(), xml, validationMode);
            }
            catch (Exception e)
            {
                log.WriteLine("Failed to build source document: " + e.Message);
                return(e);
            }
            try
            {
                sheet = compiler.CompileAssociatedStylesheet(source);
            }
            catch (Exception e)
            {
                log.WriteLine("Failed to compile stylesheet: " + e.Message);
                if (errors.Count > 0)
                {
                    return((Exception)errors[0]);
                    //QName code = ((StaticError)errors[0]).ErrorCode;
                    //(code == null ? "Failed to compile stylesheet: " + e.Message : code.LocalName);
                }
                else
                {
                    return(e);
                }
            }
        }
        else
        {
            Stream stream = new FileStream(xsl, FileMode.Open, FileAccess.Read);
            compiler.BaseUri = new Uri(xsl);
            try
            {
                sheet = compiler.Compile(stream);
            }
            catch (StaticError e)
            {
                if (errors.Count > 0)
                {
                    return((StaticError)errors[0]);
                }
                else
                {
                    log.WriteLine(e.Message);
                    return(e);
                }
            }
            catch (Exception e2)
            {
                log.WriteLine("Unexpected CRASH: " + e2.Message);
                log.WriteLine(e2.StackTrace);
                return(e2);
            }
            finally
            {
                stream.Close();
            }
        }
        if (initialContextPath != null)
        {
            if (source == null && xml != null)
            {
                try
                {
                    source = buildSource(f.NewDocumentBuilder(), xml, validationMode);
                }
                catch (Exception e)
                {
                    log.WriteLine("Failed to build source document: " + e.Message);
                    return(e);
                }
            }

            XPathCompiler   xc  = f.NewXPathCompiler();
            XPathExecutable exp = xc.Compile(initialContextPath);
            XPathSelector   xpe = exp.Load();
            xpe.ContextItem = source;
            XdmNode node = (XdmNode)xpe.EvaluateSingle();
            source = node;
        }

        inst = sheet.Load();
        if (source != null)
        {
            inst.InitialContextNode = source;
        }

        if (source == null && xml != null)
        {
            Stream stream = new FileStream(xml, FileMode.Open, FileAccess.Read);
            inst.SetInputStream(stream, new Uri(xml));
        }


        if (initialMode != null)
        {
            inst.InitialMode = initialMode;
        }
        if (initialTemplate != null)
        {
            try
            {
                inst.InitialTemplate = initialTemplate;
            }
            catch (DynamicError e)
            {
                return(e);
            }
        }
        if (paramTable != null)
        {
            foreach (DictionaryEntry de in paramTable)
            {
                inst.SetParameter((QName)de.Key, new XdmAtomicValue(de.Value.ToString()));
            }
        }

        inst.BaseOutputUri  = new Uri(outfile);
        inst.RecoveryPolicy = recoverRecoverable ? RecoveryPolicy.RecoverSilently : RecoveryPolicy.DoNotRecover;

        if ("strict" == validationMode)
        {
            inst.SchemaValidationMode = SchemaValidationMode.Strict;
        }
        else
        {
            inst.SchemaValidationMode = SchemaValidationMode.None;
        }

        //inst.setURIResolver(factory.getURIResolver());
        //inst.setErrorListener(errorListener);
        //((Controller)inst).setRecoveryPolicy(recoverRecoverable ? Configuration.RECOVER_SILENTLY : Configuration.DO_NOT_RECOVER);
        // To avoid test results being dependent on the date and time (and timezone), set a fixed
        // date and time for the run
        //((Controller)inst).setCurrentDateTime(new DateTimeValue("2005-01-01T12:49:30.5+01:00"));

        try
        {
            inst.Run(sr);
        }
        catch (DynamicError e)
        {
            log.WriteLine(e.Message);
            return(e);
        }
        catch (Exception e2)
        {
            log.WriteLine("Unexpected CRASH: " + e2.Message);
            log.WriteLine(e2.StackTrace);
            return(e2);
        }
        return(null);    // indicating success
    }
Exemplo n.º 23
0
        private static string TransformSAXON(string document, string xslt, string tmpDir)
        {
            try
            {
                Processor    processor    = new Processor();
                XsltCompiler xsltCompiler = processor.NewXsltCompiler();

                if (!Directory.Exists(tmpDir))
                {
                    tmpDir = Path.GetTempPath();
                }

                string tmpXsltFile = tmpDir + "tmp.xslt";
                File.WriteAllText(tmpXsltFile, xslt, Encoding.UTF8);
                XsltExecutable xsltExecutable = xsltCompiler.Compile(new Uri(@"file://" + tmpXsltFile));

                int    si   = document.IndexOf("xmlns:xsi=\"");
                int    ei   = document.IndexOf("\"", si + "xmlns:xsi=\"".Length) + 1;
                string text = document.Remove(si, ei - si);
                si = text.IndexOf("xmlns=\"");
                ei = text.IndexOf("\"", si + "xmlns=\"".Length) + 1;
                string xmlns = text.Substring(si, ei - si);
                text = text.Remove(si, ei - si);

                string tmpDoc = tmpDir + "tmp.xml";

                File.WriteAllText(tmpDoc, text.Replace("utf-16", "utf-8"), Encoding.UTF8);


                //StringBuilder outputBuilder = new StringBuilder();
                //XmlWriterSettings outputWriterSettings = new XmlWriterSettings { Indent = true, CheckCharacters = false, NewLineOnAttributes = true};
                //XmlWriter outputWriter = XmlWriter.Create(outputBuilder, outputWriterSettings);
                //Debug.Assert(outputWriter != null);
                //XsltArgumentList xsltArgumentList = new XsltArgumentList();

                FileStream fs = null;
                try
                {
                    XsltTransformer xsltTransformer = xsltExecutable.Load();

                    fs = new FileStream(tmpDoc, FileMode.Open);
                    xsltTransformer.SetInputStream(fs, new Uri(@"file://" + tmpDoc));
                    XdmDestination destination = new XdmDestination();
                    xsltTransformer.Run(destination);

                    StringBuilder outputBuilder = new StringBuilder();
                    outputBuilder.Append(destination.XdmNode.OuterXml);
                    //outputWriter.Flush();
                    int pos1 = outputBuilder.ToString().IndexOf(">");
                    int pos2 = outputBuilder.ToString().IndexOf("/>");
                    int pos;
                    if (pos1 == -1)
                    {
                        pos = pos2;
                    }
                    else if (pos2 == -1)
                    {
                        pos = pos1;
                    }
                    else
                    {
                        pos = Math.Min(pos1, pos2);
                    }
                    outputBuilder.Insert(pos,
                                         Environment.NewLine + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + xmlns);
                    XmlDocument  d            = new XmlDocument();
                    StringReader outputReader = new StringReader(outputBuilder.ToString());
                    d.Load(outputReader);
                    outputReader.Close();
                    return(d.PrettyPrintXML());
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.Message);
                return(string.Empty);
            }
        }
Exemplo n.º 24
0
        public static string XsltTransformSaxon(dynamic Input, string XSLT, XsltParameter[] XSLTParameters)
        {
            string BaseUri   = "";
            var    processor = new Processor();
            var    compiler  = processor.NewXsltCompiler();

            compiler.ErrorList = new List <object>();
            var xmlString = "";

            if (Input.GetType() == typeof(string))
            {
                xmlString = (string)Input;
            }
            else if (Input.GetType() == typeof(XmlDocument))
            {
                var xmlDoc = (XmlDocument)Input;
                using (var stringWriter = new StringWriter())
                    using (var xmlTextWriter = XmlWriter.Create(stringWriter))
                    {
                        xmlDoc.WriteTo(xmlTextWriter);
                        xmlTextWriter.Flush();
                        xmlString = stringWriter.GetStringBuilder().ToString();
                        //new ICSharpCode.AvalonEdit.TextEditor
                    }
            }
            else
            {
                throw new FormatException("Unsupported input type. The supported types are XmlDocument and String.");
            }

            var error = CheckForStackoverflow(XSLT);

            if (error != null)
            {
                return(error);
            }


            using (var stringReader = new StringReader(XSLT))
            {
                XsltExecutable executable = null;
                try
                {
                    executable = compiler.Compile(stringReader);
                }
                catch (Exception ex)
                {
                    var staticErrors  = string.Join(Environment.NewLine, ((List <object>)compiler.ErrorList).OfType <StaticError>().Select(o => $"{o.Message} at line {o.LineNumber}, column {o.ColumnNumber}").Distinct());
                    var dynamicErrors = string.Join(Environment.NewLine, ((List <object>)compiler.ErrorList).OfType <DynamicError>().Select(o => $"{o.Message} at line {o.LineNumber}").Distinct());
                    var errorsStr     = staticErrors + Environment.NewLine + dynamicErrors;
                    if (string.IsNullOrWhiteSpace(errorsStr))
                    {
                        throw;
                    }
                    else
                    {
                        throw new Exception(ex.Message, new Exception(errorsStr));
                    }
                }
                var transformer = executable.Load();
                var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
                var uri         = string.IsNullOrEmpty(BaseUri) ? new Uri("file://") : new Uri(BaseUri);
                transformer.SetInputStream(inputStream, uri);
                if (XSLTParameters != null)
                {
                    XSLTParameters.ToList().ForEach(x => transformer.SetParameter(new QName(x.Name), new XdmAtomicValue(x.Value)));
                }

                using (var stringWriter = new StringWriter())
                {
                    var serializer = new Serializer();
                    serializer.SetOutputWriter(stringWriter);
                    transformer.Run(serializer);
                    var output = stringWriter.GetStringBuilder().ToString();
                    output = output.Replace("\n", Environment.NewLine);
                    return(output);
                }
            }
        }
Exemplo n.º 25
0
        protected override void runTestCase(XdmNode testCase, XPathCompiler xpath)
        {
            TestOutcome outcome     = new TestOutcome(this);
            string      testName    = testCase.GetAttributeValue(new QName("name"));
            string      testSetName = testCase.Parent.GetAttributeValue(new QName("name"));

            ////
            if (testName.Equals("type-0174"))
            {
                int num = 0;
                System.Console.WriteLine("Test driver" + num);
            }

            ///
            if (exceptionsMap.ContainsKey(testName))
            {
                notrun++;
                resultsDoc.writeTestcaseElement(testName, "notRun", exceptionsMap[testName].GetAttributeValue(new QName("reason")));
                return;
            }

            if (exceptionsMap.ContainsKey(testName) || isSlow(testName))
            {
                notrun++;
                resultsDoc.writeTestcaseElement(testName, "notRun", "requires excessive resources");
                return;
            }



            XdmValue specAtt = (XdmValue)(xpath.EvaluateSingle("(/test-set/dependencies/spec/@value, ./dependencies/spec/@value)[last()]", testCase));
            string   spec    = specAtt.ToString();

            Environment env = getEnvironment(testCase, xpath);

            if (env == null)
            {
                resultsDoc.writeTestcaseElement(testName, "notRun", "test catalog error");
                return;
            }

            /*if(testName("environment-variable")) {
             *              EnvironmentVariableResolver resolver = new EnvironmentVariableResolver() {
             *          public Set<string> getAvailableEnvironmentVariables() {
             *              Set<string> strings = new HashSet<string>();
             *              strings.add("QTTEST");
             *              strings.add("QTTEST2");
             *              strings.add("QTTESTEMPTY");
             *              return strings;
             *          }
             *
             *          public string getEnvironmentVariable(string name) {
             *              if (name.Equals("QTTEST")) {
             *                  return "42";
             *              } else if (name.Equals("QTTEST2")) {
             *                  return "other";
             *              } else if (name.Equals("QTTESTEMPTY")) {
             *                  return "";
             *              } else {
             *                  return null;
             *              }
             *          }
             *      }; //TODO
             *  } */
            //   env.processor.SetProperty(JFeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER, resolver); //TODO

            XdmNode testInput  = (XdmNode)xpath.EvaluateSingle("test", testCase);
            XdmNode stylesheet = (XdmNode)xpath.EvaluateSingle("stylesheet", testInput);
            XdmNode pack       = (XdmNode)xpath.EvaluateSingle("package", testInput);


            foreach (XdmItem dep in xpath.Evaluate("(/test-set/dependencies/*, ./dependencies/*)", testCase))
            {
                if (!dependencyIsSatisfied((XdmNode)dep, env))
                {
                    notrun++;
                    resultsDoc.writeTestcaseElement(testName, "notRun", "dependency not satisfied");
                    return;
                }
            }

            XsltExecutable sheet = env.xsltExecutable;
            //ErrorCollector collector = new ErrorCollector();
            string         baseOutputURI       = resultsDir + "/results/output.xml";
            ErrorCollector collector           = new ErrorCollector(outcome);
            IList          errorList           = new List <StaticError> ();
            XmlUrlResolver res                 = new XmlUrlResolver();
            string         xsltLanguageVersion = spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0";

            if (stylesheet != null)
            {
                XsltCompiler compiler = env.xsltCompiler;
                compiler.ErrorList = errorList;
                Uri    hrefFile = res.ResolveUri(stylesheet.BaseUri, stylesheet.GetAttributeValue(new QName("file")));
                Stream stream   = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read);
                compiler.BaseUri             = hrefFile;
                compiler.XsltLanguageVersion = (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0");

                foreach (XdmItem param in xpath.Evaluate("param[@static='yes']", testInput))
                {
                    String   name   = ((XdmNode)param).GetAttributeValue(new QName("name"));
                    String   select = ((XdmNode)param).GetAttributeValue(new QName("select"));
                    XdmValue value;
                    try {
                        value = xpath.Evaluate(select, null);
                    } catch (Exception e) {
                        Console.WriteLine("*** Error evaluating parameter " + name + ": " + e.Message);
                        //throw e;
                        continue;
                    }
                    compiler.SetParameter(new QName(name), value);
                }

                try
                {
                    sheet = compiler.Compile(stream);
                } catch (Exception err) {
                    Console.WriteLine(err.Message);
                    //Console.WriteLine(err.StackTrace);
                    IEnumerator enumerator = errorList.GetEnumerator();
                    bool        checkCur   = enumerator.MoveNext();

                    /*if (checkCur && enumerator.Current != null) {
                     *      outcome.SetException ((Exception)(enumerator.Current));
                     * } else {
                     *      Console.WriteLine ("Error: Unknown exception thrown");
                     * }*/
                    outcome.SetErrorsReported(errorList);

                    //outcome.SetErrorsReported(collector.GetErrorCodes);
                }


                //  compiler.setErrorListener(collector);
            }
            else if (pack != null)
            {
                Uri    hrefFile = res.ResolveUri(pack.BaseUri, pack.GetAttributeValue(new QName("file")));
                Stream stream   = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read);

                XsltCompiler compiler = env.xsltCompiler;
                compiler.ErrorList           = errorList;
                compiler.XsltLanguageVersion = (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0");
                //compiler.setErrorListener(collector);

                try {
                    XsltPackage xpack = compiler.CompilePackage(stream);
                    sheet = xpack.Link();
                } catch (Exception err) {
                    Console.WriteLine(err.Message);
                    IEnumerator enumerator = errorList.GetEnumerator();
                    enumerator.MoveNext();
                    outcome.SetException((Exception)(enumerator.Current));
                    outcome.SetErrorsReported(errorList);
                }
            }

            if (sheet != null)
            {
                XdmItem contextItem     = env.contextItem;
                XdmNode initialMode     = (XdmNode)xpath.EvaluateSingle("initial-mode", testInput);
                XdmNode initialFunction = (XdmNode)xpath.EvaluateSingle("initial-function", testInput);
                XdmNode initialTemplate = (XdmNode)xpath.EvaluateSingle("initial-template", testInput);

                QName initialModeName     = GetQNameAttribute(xpath, testInput, "initial-mode/@name");
                QName initialTemplateName = GetQNameAttribute(xpath, testInput, "initial-template/@name");

                if (useXslt30Transformer)
                {
                    try {
                        bool    assertsSerial         = xpath.Evaluate("result//(assert-serialization|assert-serialization-error|serialization-matches)", testCase).Count > 0;
                        bool    resultAsTree          = env.outputTree;
                        bool    serializationDeclared = env.outputSerialize;
                        XdmNode needsTree             = (XdmNode)xpath.EvaluateSingle("output/@tree", testInput);
                        if (needsTree != null)
                        {
                            resultAsTree = needsTree.StringValue.Equals("yes");
                        }
                        XdmNode needsSerialization = (XdmNode)xpath.EvaluateSingle("output/@serialize", testInput);
                        if (needsSerialization != null)
                        {
                            serializationDeclared = needsSerialization.StringValue.Equals("yes");
                        }
                        bool resultSerialized = serializationDeclared || assertsSerial;

                        if (assertsSerial)
                        {
                            String comment = outcome.GetComment();
                            comment = (comment == null ? "" : comment) + "*Serialization " + (serializationDeclared ? "declared* " : "required* ");
                            outcome.SetComment(comment);
                        }


                        Xslt30Transformer transformer = sheet.Load30();
                        transformer.InputXmlResolver = env;
                        if (env.unparsedTextResolver != null)
                        {
                            transformer.GetUnderlyingController.setUnparsedTextURIResolver(env.unparsedTextResolver);
                        }

                        Dictionary <QName, XdmValue> caseGlobalParams = GetNamedParameters(xpath, testInput, false, false);
                        Dictionary <QName, XdmValue> caseStaticParams = GetNamedParameters(xpath, testInput, true, false);
                        Dictionary <QName, XdmValue> globalParams     = new Dictionary <QName, XdmValue>(env.params1);

                        foreach (KeyValuePair <QName, XdmValue> entry in caseGlobalParams)
                        {
                            globalParams.Add(entry.Key, entry.Value);
                        }

                        foreach (KeyValuePair <QName, XdmValue> entry in caseStaticParams)
                        {
                            globalParams.Add(entry.Key, entry.Value);
                        }


                        transformer.SetStylesheetParameters(globalParams);

                        if (contextItem != null)
                        {
                            transformer.GlobalContextItem = contextItem;
                        }

                        transformer.MessageListener = collector;

                        transformer.BaseOutputURI = baseOutputURI;

                        transformer.MessageListener = new TestOutcome.MessageListener(outcome);

                        XdmValue result = null;

                        TextWriter sw = new StringWriter();

                        Serializer serializer = env.processor.NewSerializer();

                        serializer.SetOutputWriter(sw);
                        //serializer.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");

                        OutputResolver          serializingOutput = new OutputResolver(env.processor, outcome, true);
                        net.sf.saxon.Controller controller        = transformer.GetUnderlyingController;

                        controller.setOutputURIResolver(serializingOutput);
                        XmlDestination dest = null;
                        if (resultAsTree)
                        {
                            // If we want non-serialized, we need to accumulate any result documents as trees too
                            controller.setOutputURIResolver(
                                new OutputResolver(env.processor, outcome, false));
                            dest = new XdmDestination();
                        }
                        if (resultSerialized)
                        {
                            dest = serializer;
                        }

                        Stream          src        = null;
                        Uri             srcBaseUri = new Uri("http://uri");
                        XdmNode         srcNode    = null;
                        DocumentBuilder builder2   = env.processor.NewDocumentBuilder();

                        if (env.streamedPath != null)
                        {
                            src        = new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read);
                            srcBaseUri = new Uri(env.streamedPath);
                        }
                        else if (env.streamedContent != null)
                        {
                            byte[] byteArray = Encoding.UTF8.GetBytes(env.streamedContent);
                            src = new MemoryStream(byteArray);                            //, "inlineDoc");
                            builder2.BaseUri = new Uri("http://uri");
                        }
                        else if (initialTemplate == null && contextItem != null)
                        {
                            srcNode = (XdmNode)(contextItem);
                        }

                        if (initialMode != null)
                        {
                            QName name = GetQNameAttribute(xpath, initialMode, "@name");
                            try {
                                if (name != null)
                                {
                                    transformer.InitialMode = name;
                                }
                                else
                                {
                                    controller.getInitialMode();                                       /// has the side effect of setting to the unnamed
                                }
                            } catch (Exception e) {
                                if (e.InnerException is net.sf.saxon.trans.XPathException)
                                {
                                    Console.WriteLine(e.Message);
                                    outcome.SetException(e);
                                    //throw new SaxonApiException(e.getCause());
                                }
                                else
                                {
                                    throw e;
                                }
                            }
                        }
                        if (initialMode != null || initialTemplate != null)
                        {
                            XdmNode init = (XdmNode)(initialMode == null ? initialTemplate : initialMode);
                            Dictionary <QName, XdmValue> params1         = GetNamedParameters(xpath, init, false, false);
                            Dictionary <QName, XdmValue> tunnelledParams = GetNamedParameters(xpath, init, false, true);
                            if (xsltLanguageVersion.Equals("2.0"))
                            {
                                if (!(params1.Count == 0 && tunnelledParams.Count == 0))
                                {
                                    Console.WriteLine("*** Initial template parameters ignored for XSLT 2.0");
                                }
                            }
                            else
                            {
                                transformer.SetInitialTemplateParameters(params1, false);
                                transformer.SetInitialTemplateParameters(tunnelledParams, true);
                            }
                        }


                        if (initialTemplate != null)
                        {
                            QName name = GetQNameAttribute(xpath, initialTemplate, "@name");
                            transformer.GlobalContextItem = contextItem;
                            if (dest == null)
                            {
                                result = transformer.CallTemplate(name);
                            }
                            else
                            {
                                transformer.CallTemplate(name, dest);
                            }
                        }
                        else if (initialFunction != null)
                        {
                            QName      name    = getQNameAttribute(xpath, initialFunction, "@name");
                            XdmValue[] params2 = getParameters(xpath, initialFunction);
                            if (dest == null)
                            {
                                result = transformer.CallFunction(name, params2);
                            }
                            else
                            {
                                transformer.CallFunction(name, params2, dest);
                            }
                        }
                        else
                        {
                            if (dest == null)
                            {
                                if (src != null)
                                {
                                    result = transformer.ApplyTemplates(src, srcBaseUri);
                                }
                                else
                                {
                                    result = transformer.ApplyTemplates(srcNode);
                                }
                            }
                            else
                            {
                                if (src != null)
                                {
                                    transformer.ApplyTemplates(src, dest);
                                }
                                else
                                {
                                    transformer.ApplyTemplates(srcNode, dest);
                                }
                            }
                        }

                        //outcome.SetWarningsReported(collector.getFoundWarnings());
                        if (resultAsTree && !resultSerialized)
                        {
                            result = ((XdmDestination)(dest)).XdmNode;
                        }
                        if (resultSerialized)
                        {
                            outcome.SetPrincipalSerializedResult(sw.ToString());
                        }
                        outcome.SetPrincipalResult(result);

                        if (saveResults)
                        {
                            String s = sw.ToString();
                            // If a transform result is entirely xsl:result-document, then result will be null
                            if (!resultSerialized && result != null)
                            {
                                StringWriter sw2 = new StringWriter();
                                Serializer   se  = env.processor.NewSerializer(sw2);
                                se.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
                                env.processor.WriteXdmValue(result, se);
                                se.Close();
                                s = sw2.ToString();
                            }
                            // currently, only save the principal result file in the result directory
                            saveResultsToFile(s, resultsDir + "/results/" + testSetName + "/" + testName + ".out");
                            Dictionary <Uri, TestOutcome.SingleResultDoc> xslResultDocuments = outcome.GetSecondaryResultDocuments();
                            foreach (KeyValuePair <Uri, TestOutcome.SingleResultDoc> entry in xslResultDocuments)
                            {
                                Uri    key           = entry.Key;
                                String path          = key.AbsolutePath;
                                String serialization = outcome.Serialize(env.processor, entry.Value);

                                saveResultsToFile(serialization, path);
                            }
                        }
                    } catch (Exception err) {
                        //if (err.getCause() is XPathException &&
                        //!((XPathException) err.getCause()).hasBeenReported()) {
                        //System.err.println("Unreported ERROR: " + err.getCause());
                        //}
                        outcome.SetException(err);
                        if (collector.getErrorCodes().Count > 0)
                        {
                            outcome.SetErrorsReported((IList)collector.getErrorCodes());
                        }
                        //Console.WriteLine(err.StackTrace);

                        /*if(err.getErrorCode() == null) {
                         *  int b = 3 + 4;  }
                         * if(err.getErrorCode() != null)
                         * outcome.AddReportedError(err.getErrorCode().getLocalName());
                         * } else {
                         * outcome.SetErrorsReported(collector.getErrorCodes());
                         * }*/
                    }                     /*catch (Exception err) {
                                           *    err.printStackTrace();
                                           *    failures++;
                                           *    resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.getClass() + ": " + err.getMessage());
                                           *    return;
                                           * }*/
                }
                else
                {
                    try {
                        XsltTransformer transformer = sheet.Load();

                        //transformer.SetURIResolver(env); //TODO
                        if (env.unparsedTextResolver != null)
                        {
                            transformer.Implementation.setUnparsedTextURIResolver(env.unparsedTextResolver);
                        }
                        if (initialTemplate != null)
                        {
                            transformer.InitialTemplate = initialTemplateName;
                        }
                        if (initialMode != null)
                        {
                            transformer.InitialMode = initialModeName;
                        }
                        foreach (XdmItem param in xpath.Evaluate("param", testInput))
                        {
                            string   name   = ((XdmNode)param).GetAttributeValue(new QName("name"));
                            string   select = ((XdmNode)param).GetAttributeValue(new QName("select"));
                            XdmValue value  = xpath.Evaluate(select, null);
                            transformer.SetParameter(new QName(name), value);
                        }
                        if (contextItem != null)
                        {
                            transformer.InitialContextNode = (XdmNode)contextItem;
                        }
                        if (env.streamedPath != null)
                        {
                            transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri);
                        }
                        foreach (QName varName in env.params1.Keys)
                        {
                            transformer.SetParameter(varName, env.params1[varName]);
                        }
                        //transformer.setErrorListener(collector);
                        transformer.BaseOutputUri = new Uri(resultsDir + "/results/output.xml");

                        /*transformer.MessageListener = (new MessageListener() {
                         *  public void message(XdmNode content, bool terminate, SourceLocator locator) {
                         *      outcome.addXslMessage(content);
                         *  }
                         * });*/


                        // Run the transformation twice, once for serialized results, once for a tree.
                        // TODO: we could be smarter about this and capture both

                        // run with serialization
                        StringWriter sw         = new StringWriter();
                        Serializer   serializer = env.processor.NewSerializer(sw);
                        transformer.Implementation.setOutputURIResolver(new OutputResolver(driverProc, outcome, true));


                        transformer.Run(serializer);

                        outcome.SetPrincipalSerializedResult(sw.ToString());
                        if (saveResults)
                        {
                            // currently, only save the principal result file
                            saveResultsToFile(sw.ToString(),
                                              resultsDir + "/results/" + testSetName + "/" + testName + ".out");
                        }
                        transformer.MessageListener = new TestOutcome.MessageListener(outcome);

                        // run without serialization
                        if (env.streamedPath != null)
                        {
                            transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri);
                        }
                        XdmDestination destination = new XdmDestination();
                        transformer.Implementation.setOutputURIResolver(
                            new OutputResolver(env.processor, outcome, false));
                        transformer.Run(destination);

                        //transformer. .transform();
                        outcome.SetPrincipalResult(destination.XdmNode);
                        //}
                    } catch (Exception err) {
                        outcome.SetException(err);
                        //outcome.SetErrorsReported(collector.getErrorCodes());
                        // err.printStackTrace();
                        // failures++;
                        //resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.Message);
                        //return;
                    }
                }
                XdmNode assertion = (XdmNode)xpath.EvaluateSingle("result/*", testCase);
                if (assertion == null)
                {
                    failures++;
                    resultsDoc.writeTestcaseElement(testName, "fail", "No test assertions found");
                    return;
                }
                XPathCompiler assertionXPath = env.processor.NewXPathCompiler();
                //assertionXPath.setLanguageVersion("3.0");
                bool success = outcome.TestAssertion(assertion, outcome.GetPrincipalResultDoc(), assertionXPath, xpath, debug);
                if (success)
                {
                    if (outcome.GetWrongErrorMessage() != null)
                    {
                        outcome.SetComment(outcome.GetWrongErrorMessage());
                        wrongErrorResults++;
                    }
                    else
                    {
                        successes++;
                    }
                    resultsDoc.writeTestcaseElement(testName, "pass", outcome.GetComment());
                }
                else
                {
                    failures++;
                    resultsDoc.writeTestcaseElement(testName, "fail", outcome.GetComment());
                }
            }
        }
Exemplo n.º 26
0
        private static string TransformSAXON(string document, string xslt, string tmpDir, PSMSchema psmSchema = null, bool schemaAware = false)
        {
            Processor    processor    = new Processor();
            XsltCompiler xsltCompiler = processor.NewXsltCompiler();

            //xsltCompiler.SchemaAware = true;
            xsltCompiler.Processor.SetProperty(FeatureKeys.GENERATE_BYTE_CODE, "false");

            if (!Directory.Exists(tmpDir))
            {
                tmpDir = Path.GetTempPath();
            }

            using (StringReader sr = new StringReader(xslt))
            {
                XsltExecutable xsltExecutable = xsltCompiler.Compile(sr);

                string text;

                if (!schemaAware)
                {
                    int si = document.IndexOf("xmlns:xsi=\"");
                    int ei = document.IndexOf("\"", si + "xmlns:xsi=\"".Length) + 1;
                    text = si != -1 ? document.Remove(si, ei - si) : document;
                    si   = text.IndexOf("xmlns=\"");
                    ei   = text.IndexOf("\"", si + "xmlns=\"".Length) + 1;
                    string xmlns = si != -1 ? text.Substring(si, ei - si) : string.Empty;
                    text = si != -1 ? text.Remove(si, ei - si) : text;
                }
                else
                {
                    text = document;
                }

                string tmpDoc = tmpDir + "tmp.xml";

                if (schemaAware)
                {
                    XsdSchemaGenerator xsdGen = new XsdSchemaGenerator();
                    xsdGen.Initialize(psmSchema);
                    xsdGen.GenerateXSDStructure();
                    XDocument schema    = xsdGen.GetXsd();
                    string    schemaLoc = tmpDir + "LastSchema.xsd";
                    schema.Save(schemaLoc);
                }

                File.WriteAllText(tmpDoc, text.Replace("utf-16", "utf-8"), Encoding.UTF8);


                StringBuilder outputBuilder = new StringBuilder();
                //XmlWriterSettings outputWriterSettings = new XmlWriterSettings { Indent = true, CheckCharacters = false, NewLineOnAttributes = true };
                //XmlWriter outputWriter = XmlWriter.Create(outputBuilder, outputWriterSettings);
                //Debug.Assert(outputWriter != null);
                XsltArgumentList xsltArgumentList = new XsltArgumentList();
                FileStream       fs = null;
                try
                {
                    XsltTransformer xsltTransformer = xsltExecutable.Load();
                    if (schemaAware)
                    {
                        xsltTransformer.SchemaValidationMode = SchemaValidationMode.Strict;
                    }

                    fs = new FileStream(tmpDoc, FileMode.Open);
                    xsltTransformer.SetInputStream(fs, new Uri(@"file://" + tmpDoc));
                    XdmDestination destination = new XdmDestination();
                    xsltTransformer.Run(destination);

                    outputBuilder.Append(destination.XdmNode.OuterXml);
                    //outputWriter.Flush();
                    int pos1 = outputBuilder.ToString().IndexOf(">");
                    int pos2 = outputBuilder.ToString().IndexOf("/>");
                    int pos;
                    if (pos1 == -1)
                    {
                        pos = pos2;
                    }
                    else if (pos2 == -1)
                    {
                        pos = pos1;
                    }
                    else
                    {
                        pos = Math.Min(pos1, pos2);
                    }
                    //outputBuilder.Insert(pos,
                    //                     Environment.NewLine + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + xmlns);

                    StringReader outputReader = new StringReader(outputBuilder.ToString());
                    XDocument    d            = XDocument.Load(outputReader);
                    outputReader.Close();
                    return(d.PrettyPrintXML());
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
            }
        }