Exemple #1
8
        public static void Transform(Uri StyleSheet, String Input,Encoding Encoding,out String Output)
        {
            Processor processor = new Processor();

            XdmNode input = processor.NewDocumentBuilder().Build(new XmlTextReader(new StringReader(Input)));

            processor.SetProperty("http://saxon.sf.net/feature/preferJaxpParser", "true");

            XsltCompiler compiler = processor.NewXsltCompiler();

            XsltExecutable executable = compiler.Compile(StyleSheet);

            XsltTransformer transformer = executable.Load();

            transformer.InitialContextNode = input;

            Serializer serializer = new Serializer();

            MemoryStream stream = new MemoryStream();

            System.IO.StreamWriter writer = new StreamWriter(stream);

            serializer.SetOutputWriter(writer);

            transformer.Run(serializer);

            Output = Encoding.GetString(stream.ToArray());

            writer.Close();

            stream.Close();
        }
Exemple #2
1
        static void Main(string[] args)
        {
            String s1 = @"<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:output method='xml' indent='yes'/><xsl:template match='/'>";
            String s2 = "This is running an XSLT engine by <xsl:value-of select=\"system-property('xsl:vendor')\" />  <a href=\"{system-property('xsl:vendor-url')}\"><xsl:value-of select=\"system-property('xsl:vendor-url')\" /></a> implementing XSLT v<xsl:value-of select=\"system-property('xsl:version')\" /> ";
            String s3 = @"\n<xsl:apply-templates/></xsl:template><xsl:template match='@*|node()'> ";
            String s4 = @"<xsl:copy><xsl:apply-templates select='@*|node()'/></xsl:copy></xsl:template></xsl:stylesheet>";

            String str = s1 + s2 + s3  + s4;

            //Run Saxon
            //new SaxonTransform().doTransform(args, "Transform");

            //Run Saxon s9 api
            // Create a Processor instance.
            Processor processor = new Processor();

            // Load the source document.
            XdmNode input = processor.NewDocumentBuilder().Build(XmlReader.Create(new StringReader(str)));

            XsltCompiler compiler = processor.NewXsltCompiler();
            //although it is not required in this example, we need to set otherwise exception will be thrown
            compiler.BaseUri = new Uri("http://dummyurl.com");
            // Create a transformer for the stylesheet.
            XsltTransformer transformer = compiler.Compile(XmlReader.Create(new StringReader(str))).Load();

            // BaseOutputUri is only necessary for xsl:result-document.
            //transformer.BaseOutputUri = new Uri("http://dummyurl.com");
            // Set the root node of the source document to be the initial context node.
            transformer.InitialContextNode = input;

            transformer.SetParameter(new QName("", "", "maxmin"), new XdmAtomicValue("parm1"));
            transformer.SetParameter(new QName("", "", "pricestock"), new XdmAtomicValue("parm2"));

            // Create a serializer.
            Serializer serializer = new Serializer();

            // Set the root node of the source document to be the initial context node
            //transformer.InitialTemplate = new QName("","","go");

            serializer.SetOutputWriter(Console.Out);
            serializer.SetOutputProperty(Serializer.INDENT, "yes");

            // serializer.SetOutputFile(Server.MapPath("test.html")); //for file

            // Transform the source XML to System.out.
            transformer.Run(serializer);

            //Call the SaxonMediator
            SaxonMediator mediator = new SaxonMediator();

            //mediator.Transform(null, Template template, Package package)

            //wait for user to exit
            Console.ReadLine();
        }
Exemple #3
0
 public Xsl2Processor()
 {
     // Create a Processor instance.
     _processor = new Processor();
     _compiler = _processor.NewXsltCompiler();
     
 }
Exemple #4
0
        public static void Transform(String StylesheetFilename, String SourceFilename, String OutputFilename)
        {
            if (StylesheetFilename.StartsWith(".\\"))
            {
                StylesheetFilename = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + StylesheetFilename;
            }

            Processor processor = new Processor();

            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(SourceFilename));

            processor.SetProperty("http://saxon.sf.net/feature/preferJaxpParser", "true");

            XsltCompiler compiler = processor.NewXsltCompiler();

            XsltExecutable executable = compiler.Compile(new Uri(StylesheetFilename));

            XsltTransformer transformer = executable.Load();

            transformer.InitialContextNode = input;

            Serializer serializer = new Serializer();

            System.IO.StreamWriter stream = new StreamWriter(OutputFilename);

            serializer.SetOutputWriter(stream);

            transformer.Run(serializer);

            stream.Close();
        }
Exemple #5
0
        // internal constructor: the public interface is a factory method
        // on the Processor object

        internal XQueryCompiler(Processor processor)
        {
            this.processor = processor;
            this.config = processor.config;
            this.env = config.newStaticQueryContext();
            env.setModuleURIResolver(new DotNetStandardModuleURIResolver(processor.XmlResolver));
        }
Exemple #6
0
        // internal constructor: the public interface is a factory method
        // on the Processor object

        internal XsltCompiler(Processor processor)
        {
            this.processor = processor;
            this.config = processor.config;
            this.factory = new TransformerFactoryImpl(config);
            this.info = new JCompilerInfo();
            info.setURIResolver(config.getURIResolver());
            info.setErrorListener(config.getErrorListener());
        }
        public static string ImportSchematron(string baseDir, string schemaPath, string xsltPath)
        {
            // Builds a new XSLT file from a schematron file.
            // This only needs to be done when the schematron file changes.
            var sxnProc = new Processor();

            var outPath = xsltPath;
            var baseXsltPath = Path.Combine(baseDir, @"Content\Saxon\");

            var schConverter = new string[]
                                   {
                                       baseXsltPath + "iso_dsdl_include.xsl",
                                       baseXsltPath + "iso_abstract_expand.xsl",
                                       baseXsltPath + "iso_svrl_for_xslt2.xsl"
                                   };
            var schemaUri = new Uri(schemaPath);
            var xslComp = sxnProc.NewXsltCompiler();

            //////transform-1/////
            var xslUri = new Uri(schConverter[0]);
            var xslExec = xslComp.Compile(xslUri);
            var xslTrans = xslExec.Load();
            var domOut1 = new DomDestination(new XmlDocument());
            using(var fs = File.Open(schemaPath, FileMode.Open, FileAccess.Read))
            {
                xslTrans.SetInputStream(fs, schemaUri); // set baseUri
                xslTrans.Run(domOut1);
            }

            //////transform-2/////
            xslUri = new Uri(schConverter[1]);
            xslExec = xslComp.Compile(xslUri);
            xslTrans = xslExec.Load();
            var domOut2 = new DomDestination(new XmlDocument());
            var docBuilder = sxnProc.NewDocumentBuilder();
            docBuilder.BaseUri = schemaUri;
            var inputDoc2 = docBuilder.Wrap(domOut1.XmlDocument);
            xslTrans.InitialContextNode = inputDoc2;
            xslTrans.Run(domOut2);

            //////transform-3/////
            xslUri = new Uri(schConverter[2]);
            xslExec = xslComp.Compile(xslUri);
            xslTrans = xslExec.Load();
            var inputDoc3 = docBuilder.Wrap(domOut2.XmlDocument);
            xslTrans.InitialContextNode = inputDoc3;
            var serializer = new Serializer();
            using (TextWriter tw = new StreamWriter(outPath, false))
            {
                serializer.SetOutputWriter(tw);
                serializer.SetOutputProperty(Serializer.INDENT, "no");
                xslTrans.Run(serializer);
            }

            return outPath;
        }
 private XdmNode getLinkedDocument(XdmNode element, Processor processor, bool validate)
 {
     String href = element.GetAttributeValue(xlinkHref);
     DocumentBuilder builder = processor.NewDocumentBuilder();
     Uri target = new Uri(element.BaseUri, href);
     builder.IsLineNumbering = true;
     if (validate) {
         builder.SchemaValidationMode = SchemaValidationMode.Strict;
     }
     return builder.Build(target);
 }
        public SaxonDotNetTransform(string sTransformName, string sTargetLanguageCode)
            : base(sTargetLanguageCode)
        {
            // Create a Processor instance.
            m_processor = new Processor();
            m_compiler = m_processor.NewXsltCompiler();

            // Load transform from file
            var uri = new Uri(sTransformName);
            var errorList = new List<StaticError>();
            m_compiler.ErrorList = errorList;
            var t = m_compiler.Compile(uri);
            m_transformer = t.Load();
        }
Exemple #10
0
        private void Init (HttpContext context) {
            AppSettings baseXslt = new AppSettings();
            String xsltUri = context.Server.MapPath(baseXslt.GetSetting("baseTemplate"));
            Uri xUri = new Uri(xsltUri);

            this._Resolver = new XmlUrlResolver();
            this._Resolver.Credentials = CredentialCache.DefaultCredentials;

            this._TemplateStream = (Stream)this._Resolver.GetEntity(xUri, null, typeof(Stream));
            this._Processor = new Processor();
            this._Compiler = _Processor.NewXsltCompiler();
            this._Compiler.BaseUri = xUri;
            this._Template = this._Compiler.Compile(_TemplateStream);
            this._IS_INITIALIZED = true;
        }
Exemple #11
0
    public void ProcessRequest(HttpContext context) {

      _requestMethod = context.Request.HttpMethod;
      _writer = context.Response.Output;
      _context = context;
      _processor = (Processor)context.Application["processor"];
      _compiler = (XsltCompiler)context.Application["compiler"];
      _serializer = (Serializer)context.Application["serializer"];
      _resolver = (XmlUrlResolver)context.Application["resolver"];
      _globalXsltParams = (Hashtable)context.Application["globalXsltParams"];
      _sessionXsltParams = (Hashtable)context.Application["sessionXsltParams"];
      _requestXsltParams = (Hashtable)context.Application["requestXsltParams"];
      Hashtable xsltParams = new Hashtable();
      foreach (DictionaryEntry param in _globalXsltParams) {
        xsltParams[param.Key] = param.Value;
      }
      foreach (DictionaryEntry param in _sessionXsltParams) {
        xsltParams[param.Key] = param.Value;
      }
      foreach (DictionaryEntry param in _requestXsltParams) {
        xsltParams[param.Key] = param.Value;
      }
      _transformContext = new Context(context, _processor, _compiler, _serializer, _resolver, xsltParams);

      switch (_requestMethod) {

        case "GET": {
            new Transform().Process(_transformContext);
            break;
          }
        case "PUT": {
            new Transform().Process(_transformContext);
            break;
          }
        case "POST": {
            new Transform().Process(_transformContext);
            break;
          }
        case "DELETE": {
            new Transform().Process(_transformContext);
            break;
          }
        default: {
            new Transform().Process(_transformContext);
            break;
          }
      }
    }
Exemple #12
0
        private string xml2HtmlTree()
        {
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(this.Xsd);
            StreamReader xsl = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "/Areas/MSM/Resources/Stylesheets/xsd2htmlTree.xslt");

            Processor processor = new Processor();
            XdmNode input = processor.NewDocumentBuilder().Build(xml);
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(xsl).Load();
            transformer.InitialContextNode = input;
            StringWriter writer = new StringWriter();
            Serializer serializer = new Serializer();
            serializer.SetOutputWriter(writer);
            transformer.Run(serializer);
            return writer.ToString();
        }
Exemple #13
0
        static void Main(string[] args)
        {
            string infile = @"c:\daisybooks\verysimplebook\verysimplebook.xml";
            string infile_dir = @"c:\daisybooks\verysimplebook\";
            string xsltfile = @"c:\devel\amis\trunk\amis\bin\xslt\dtbook\dtbook2xhtml.xsl";
            string outfile = @"c:\devel\amis\sandbox\dtbooktransformer_out.xml";

            // Create a Processor instance.
            Processor processor = new Processor();

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

            // Create a transformer for the stylesheet.
            XsltTransformer transformer =
                processor.NewXsltCompiler().Compile(new Uri(xsltfile)).Load();

            QName basedir = new QName("", "baseDir");

            List<XdmAtomicValue> elementNames = new List<XdmAtomicValue>();
            elementNames.Add(new XdmAtomicValue(infile_dir));
            XdmValue basedir_value = new XdmValue(elementNames);

            transformer.SetParameter(basedir, basedir_value);

            // Set the user-written XmlResolver
            UserXmlResolver runTimeResolver = new UserXmlResolver();
            runTimeResolver.Message = "** Calling transformation-time XmlResolver: ";
            transformer.InputXmlResolver = runTimeResolver;

            // Set the root node of the source document to be the initial context node
            transformer.InitialContextNode = input;

            /*
             *  String outfile = "OutputFromXsltSimple2.xml";
            Serializer serializer = new Serializer();
            serializer.SetOutputStream(new FileStream(outfile, FileMode.Create, FileAccess.Write));
            */
              // Create a serializer, with output to the standard output stream
            Serializer serializer = new Serializer();
            serializer.SetOutputWriter(Console.Out);

            // Transform the source XML and serialize the result document
            transformer.Run(serializer);

            Console.ReadLine();
        }
Exemple #14
0
        static void Main(string[] args)
        {
            if ( args.Length < 2)
            {
                Console.Error.WriteLine("Syntax: demo <path-to-xml-file> <xpath-expression> [<num-iterations(default={0})>]", numIters);
                return;
            }

            var file = args[0];
            var xpath = args[1];

            if ( args.Length > 2)
            {
                numIters = int.Parse(args[2]);
            }

            Console.WriteLine("Loading {0}", file);

            var proc = new Processor();

            var ms_xp = System.Xml.XPath.XPathExpression.Compile(xpath);

            var xpc = proc.NewXPathCompiler();
            var xpe = xpc.Compile(xpath);
            var sel = xpe.Load();

            var doc = XDocument.Load(file);
            var ctx = proc.Wrap(doc);
            sel.ContextItem = ctx;

            var nt = new NameTable();
            XmlDocument xd = new XmlDocument(nt);
            xd.Load(file);

            var ctxXmlDoc = proc.NewDocumentBuilder().Wrap(xd);

            Console.WriteLine("Evaluating {0}", xpath);

            Time(() => Saxon(sel), "XDoc (Saxon)");
            Time(() => Native(ms_xp, doc), "XDoc (Native)");

            sel.ContextItem = ctxXmlDoc;

            Time(() => Saxon(sel), "XmlDoc (Saxon)");
            Time(() => Native(ms_xp, xd), "XmlDoc (Native)");
        }
Exemple #15
0
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                // free other managed objects that implement
                // IDisposable only
            }

            // release any unmanaged objects set the object references to null
            _processor = null;
            _compiler = null;
            _transformer = null;

            _disposed = true;
        }
        /// <summary>
        /// Load the XSLT file
        /// </summary>
        public void Load(string filename, bool profilingEnabled = false)
        {
            //register our eval() function
            processor = new Processor();
            processor.RegisterExtensionFunction(new SaxonEvaluate(processor.NewXPathCompiler()));

            //tracing
            if (profilingEnabled)
            {
                var profile = new TimingTraceListener();
                processor.Implementation.setTraceListener(profile);
                processor.Implementation.setLineNumbering(true);
                processor.Implementation.setCompileWithTracing(true);
                processor.Implementation.getDefaultXsltCompilerInfo().setCodeInjector(new TimingCodeInjector());
                profile.setOutputDestination(new java.io.PrintStream("profile.html"));
            }

            //capture the error information
            var compiler = processor.NewXsltCompiler();
            compiler.ErrorList = errorList;

            //compile the stylesheet
            var relativeFilename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename);
            try
            {
                var exec = compiler.Compile(XmlTextReader.Create(relativeFilename));

                //capture xsl:message output
                transform = exec.Load();
                transform.MessageListener = new SaxonMessageListener();
            }
            catch (Exception)
            {
                foreach (StaticError err in compiler.ErrorList)
                {
                    log.ErrorFormat("{0} ({1}, line {2})", err, err.ModuleUri, err.LineNumber);
                }
                throw;
            }
        }
Exemple #17
0
      void RegisterExtensionFunctions(Processor processor, SaxonItemFactory itemFactory) {

         IEnumerable<IEnumerable<Type>> builtInFunctions = 
            new IEnumerable<Type>[] { 
               new modules.exslt.common.Index(),
               new modules.request.Index(),
               new modules.response.Index(),
               new modules.session.Index(),
               new modules.util.Index(),
               new modules.validation.Index(),
               new modules.smtpclient.Index(),
               new modules.expath.httpclient.Index(),
            };

         IEnumerable<IEnumerable<Type>> importedFunctions =
            (from m in XPathModules.GetModuleAdaptersForProcessor(this.GetType())
             let t = m.AdapterType
             let isCollection = typeof(IEnumerable<Type>).IsAssignableFrom(t)
             select (isCollection) ? 
               (IEnumerable<Type>)Activator.CreateInstance(t)
               : new Type[] { t });

         Type itemFactoryType = itemFactory.GetType();

         foreach (var types in Enumerable.Concat(builtInFunctions, importedFunctions)) {

            var functions =
               from t in types
               let ctor = t.GetConstructors().First()
               let param = ctor.GetParameters()
               let args = param.Select(p => p.ParameterType.IsAssignableFrom(itemFactoryType) ? (object)itemFactory : null).ToArray()
               select (ExtensionFunctionDefinition)ctor.Invoke(args);

            if (functions.Select(f => f.FunctionName.Uri).Distinct().Count() > 1) 
               throw new InvalidOperationException("Functions in module must belog to the same namespace.");

            foreach (var fn in functions)
               processor.RegisterExtensionFunction(fn);
         }
      }
        internal XmlDocument DoTransform()
        {
            Processor processor = new Processor();

            XdmNode input = processor.NewDocumentBuilder().Wrap(_docToTransform);

            // Create a compiler
            XsltCompiler compiler = processor.NewXsltCompiler();

            DocumentBuilder builder = processor.NewDocumentBuilder();
            XdmNode xsltSheetNode = builder.Build(_xsltDocReader);

            // Compile the stylesheet
            XsltTransformer transformer = compiler.Compile(xsltSheetNode).Load();

            // Run the transformation
            transformer.InitialContextNode = input;
            DomDestination result = new DomDestination();
            transformer.Run(result);

            return result.XmlDocument;
        }
Exemple #19
0
        private static XdmNode getXdmNode(String uri, String path) {
            try {

                SgmlReader sr = new SgmlReader();
                sr.Href = uri;

                XmlDocument htmlDoc = new XmlDocument();

                try {
                    htmlDoc.Load(sr);
                } catch (Exception e) {
                    throw;
                }

                XmlNode html = htmlDoc.SelectSingleNode(path);
                Processor processor = new Processor();
                return processor.NewDocumentBuilder().Build(html);

            } catch (Exception e) {
                throw;
            }
        }
Exemple #20
0
        public static void Main()
        {
            using (FileStream streamXml = File.OpenRead(XmlPath))
            {
                using (FileStream streamXsl = File.OpenRead(XsltPath))
                {
                    Processor processor = new Processor();

                    DocumentBuilder builder = processor.NewDocumentBuilder();
                    Uri uri = new Uri("urn:catalogue");
                    builder.BaseUri = uri;
                    XdmNode input = builder.Build(streamXml);
                    XsltTransformer transformer = processor.NewXsltCompiler().Compile(streamXsl).Load();
                    transformer.InitialContextNode = input;
                    Serializer serializer = new Serializer();
                    serializer.SetOutputFile(HtmlPath);
                    transformer.Run(serializer);
                }
            }

            Console.WriteLine("catalogue.html created successfully");
        }
 public XsltTransformationManager
   (
     Processor processor,
     Transform transform,
     XmlUrlResolver resolver,
     Serializer serializer,
     Hashtable xsltHashtable,
     Hashtable xmlSourceHashtable,
     Hashtable xdmNodeHashtable,
     Hashtable namedXsltHashtable,
     Hashtable namedXsltETagIndex,
     Hashtable xdmNodeETagIndex,
     Uri baseXsltUri,
     String baseXsltUriHash,
     String baseXsltName
   )
 {
     _baseXsltUri = baseXsltUri;
     _baseXsltUriHash = baseXsltUriHash;
     _baseXsltName = baseXsltName;
     _transform = transform;
     _xsltHashtable = xsltHashtable;
     _processor = processor;
     _compiler = _processor.NewXsltCompiler();
     _sourceHashtable = xmlSourceHashtable;
     _resolver = resolver;
     _compiler.XmlResolver = _resolver;
     _builder = _processor.NewDocumentBuilder();
     _serializer = serializer;
     _xdmNodeHashtable = xdmNodeHashtable;
     _xdmNodeETagIndex = xdmNodeETagIndex;
     _namedXsltHashtable = namedXsltHashtable;
     _namedXsltETagIndex = namedXsltETagIndex;
     _hashAlgorithm = HashAlgorithm.SHA1;
     //NOTE: TransformEngine enum PLACEHOLDER FOR FUTURE USE
     _transformEngine = TransformEngine.SAXON;
 }
Exemple #22
0
 public XsltTransformationManager
   (
     Processor processor,
     Transform transform,
     XmlUrlResolver resolver,
     Serializer serializer,
     Dictionary<string, XsltTransformer> xsltHashtable,
     Hashtable xmlSourceHashtable,
     Hashtable xdmNodeHashtable,
     Hashtable namedXsltHashtable,
     Hashtable namedXsltETagIndex,
     Hashtable xdmNodeETagIndex,
     Uri baseXsltUri,
     String baseXsltUriHash,
     String baseXsltName
   ) {
     m_baseXsltUri = baseXsltUri;
     m_baseXsltUriHash = baseXsltUriHash;
     m_baseXsltName = baseXsltName;
     m_transform = transform;
     m_xsltHashtable = xsltHashtable;
     m_processor = processor;
     m_compiler = m_processor.NewXsltCompiler();
     m_sourceHashtable = xmlSourceHashtable;
     m_resolver = resolver;
     m_compiler.XmlResolver = m_resolver;
     m_builder = m_processor.NewDocumentBuilder();
     m_serializer = serializer;
     m_xdmNodeHashtable = xdmNodeHashtable;
     m_xdmNodeETagIndex = xdmNodeETagIndex;
     m_namedXsltHashtable = namedXsltHashtable;
     m_namedXsltETagIndex = namedXsltETagIndex;
     m_hashAlgorithm = HashAlgorithm.MD5;
     //NOTE: TransformEngine enum PLACEHOLDER FOR FUTURE USE
     m_transformEngine = TransformEngine.SAXON;
 }
            /**
             * Run the tests
             * @param args command line arguments
             * @throws SAXException
             * @throws ParserConfigurationException
             * @throws XPathException
             * @throws IOException
             * @throws URISyntaxException
             */

            public void go(String[] args) {
                if (args.Length == 0 || args[0] == "-?")
                {
                    Console.WriteLine("SchemaTestSuiteDriver testDir [-w] [-onwards] -c:contributor? -s:setName? -g:groupName?");
                }
                Processor processor = new Processor(true);
                Console.WriteLine("Testing Saxon " + processor.ProductVersion);
                                
                testSuiteDir = args[0];
                if (testSuiteDir.EndsWith("/"))
                {
                    testSuiteDir = testSuiteDir.Substring(0, testSuiteDir.Length - 1);
                }
                String testSetPattern = null;   // TODO use a regex
                String testGroupPattern = null;
                String contributor = null;
                Hashtable exceptions = new Hashtable();

                for (int i=1; i<args.Length; i++) {
                    if (args[i] == ("-w")) {
                        //showWarnings = true;
                    } else if (args[i] == ("-onwards")) {
                        onwards = true;
                    } else if (args[i].StartsWith("-c:")) {
                        contributor = args[i].Substring(3);
                    } else if (args[i].StartsWith("-s:")) {
                        testSetPattern = args[i].Substring(3);
                    } else if (args[i].StartsWith("-g:")) {
                        testGroupPattern = args[i].Substring(3);
                    } else if (args[i] == "-?") {
                        Console.WriteLine("Usage: SchemaTestSuiteDriver testDir [-w] [-s:testSetPattern] [-g:testGroupPattern]");
                    }
                }

                int total = 39700;
                int passed = 0;
                int failed = 0;

                try {

                    xlinkHref = new QName("xlink", "http://www.w3.org/1999/xlink", "href");

                    QName testCaseNT = new QName("", "", "testcase");
                    QName commentNT = new QName("", "", "comment");

                    QName testSetRefNT = new QName(testNS, "testSetRef");
                    QName testGroupNT = new QName(testNS, "testGroup");
                    QName testSetNT = new QName(testNS, "testSet");
                    QName schemaTestNT = new QName(testNS, "schemaTest");
                    QName instanceTestNT = new QName(testNS, "instanceTest");
                    QName schemaDocumentNT = new QName(testNS, "schemaDocument");
                    QName instanceDocumentNT = new QName(testNS, "instanceDocument");
                    QName expectedNT = new QName(testNS, "expected");
                    QName currentNT = new QName(testNS, "current");

                    QName validityAtt = new QName("", "", "validity");
                    QName nameAtt = new QName("", "", "name");
                    QName contributorAtt = new QName("", "", "contributor");
                    QName setAtt = new QName("", "", "set");
                    QName groupAtt = new QName("", "", "group");
                    QName statusAtt = new QName("", "", "status");
                    QName bugzillaAtt = new QName("", "", "bugzilla");
                    QName targetNamespaceAtt = new QName("", "", "targetNamespace");
                    QName schemaVersion = new QName("saxon", "http://saxon.sf.net/", "schemaVersion");


                    DocumentBuilder builder = processor.NewDocumentBuilder();
                    builder.BaseUri = new Uri(testSuiteDir + "/");
                    XdmNode catalog = builder.Build(
                            new FileStream(testSuiteDir + "/suite.xml", FileMode.Open, FileAccess.Read, FileShare.Read));

                    results = new StreamWriter(testSuiteDir + "/saxon/SaxonResults"
                                + processor.ProductVersion + "n.xml");

                    results.Write("<testSuiteResults xmlns='" + testNS + "' xmlns:saxon='http://saxon.sf.net/' " +
                            "suite='TS_2006' " +
                            "processor='Saxon-SA (Java) 8.8++' submitDate='2007-01-05' publicationPermission='public'>\n");

                    XdmNode exceptionsDoc = builder.Build(
                            new FileStream(testSuiteDir + "/saxon/exceptions.xml", 
                                FileMode.Open, FileAccess.Read, FileShare.Read));

                  
                    IEnumerator exceptionTestCases = exceptionsDoc.EnumerateAxis(XdmAxis.Descendant, new QName("", "testcase"));
                    while (exceptionTestCases.MoveNext()) {
                        XdmNode testCase = (XdmNode)exceptionTestCases.Current;
                        String set = testCase.GetAttributeValue(setAtt);
                        String group = testCase.GetAttributeValue(groupAtt);
                        String comment = getChildElement(testCase, commentNT).StringValue;
                        exceptions[set + "#" + group] = comment;
                    }

                    IEnumerator testSets = catalog.EnumerateAxis(XdmAxis.Descendant, testSetRefNT);
                    while (testSets.MoveNext()) {

                        XdmNode testSetRef = (XdmNode)testSets.Current;
                        XdmNode testSetDoc = getLinkedDocument(testSetRef, processor, false);
                        XdmNode testSetElement = getChildElement(testSetDoc, testSetNT);

                        if (testSetElement == null) {
                            feedback.Message("test set doc has no TestSet child: " + testSetDoc.BaseUri, true);
                            continue;
                        }

                        String testSetName = testSetElement.GetAttributeValue(nameAtt);
                        if (testSetPattern != null && !testSetName.StartsWith(testSetPattern)) {
                            continue;
                        }
                        if (contributor != null && contributor != testSetElement.GetAttributeValue(contributorAtt)) {
                            continue;
                        }

                        bool needs11 = (testSetElement.GetAttributeValue(schemaVersion) == "1.1"); 

                        IEnumerator testGroups = testSetElement.EnumerateAxis(XdmAxis.Child, testGroupNT);
                        while (testGroups.MoveNext()) {
                            XdmNode testGroup = (XdmNode)testGroups.Current;
                            
                            String testGroupName = testGroup.GetAttributeValue(nameAtt);
                            String exception = (String)exceptions[testSetName + "#" + testGroupName];

                            if (testGroupPattern != null && !testGroupName.StartsWith(testGroupPattern)) {
                                continue;
                            }
                            Console.WriteLine("TEST SET " + testSetName + " GROUP " + testGroupName, false);
                            if (onwards) {
                                testGroupPattern = null;
                                testSetPattern = null;
                            }
                            Processor testConfig = new Processor(true);
                            if (needs11)
                            {
                                testConfig.SetProperty("http://saxon.sf.net/feature/xsd-version", "1.1");
                            }
                            SchemaManager schemaManager = testConfig.SchemaManager;
                            

                            //testConfig.setHostLanguage(Configuration.XML_SCHEMA);
                            testConfig.SetProperty("http://saxon.sf.net/feature/validation-warnings", "true");
                            IEnumerator schemaTests = testGroup.EnumerateAxis(XdmAxis.Child, schemaTestNT);
                            bool schemaQueried = false;
                            String bugzillaRef = null;

                            while (schemaTests.MoveNext()) {
                                XdmNode schemaTest = (XdmNode)schemaTests.Current;
                                if (schemaTest == null) {
                                    break;
                                }
                                bugzillaRef = null;
                                String testName = schemaTest.GetAttributeValue(nameAtt);
                                if (exception != null) {
                                    results.Write("<testResult set='" + testSetName +
                                            "' group='" + testGroupName +
                                            "' test='" + testName +
                                            "' validity='notKnown' saxon:outcome='notRun' saxon:comment='" + exception +
                                            "'/>\n");
                                    continue;
                                }
                                bool queried = false;
                                XdmNode statusElement = getChildElement(schemaTest, currentNT);
                                if (statusElement != null) {
                                    String status = statusElement.GetAttributeValue(statusAtt);
                                    queried = ("queried" == status);
                                    bugzillaRef = statusElement.GetAttributeValue(bugzillaAtt);
                                }
                                if (queried) {
                                    schemaQueried = true;
                                }
                                Console.WriteLine("TEST SCHEMA " + testName + (queried ? " (queried)" : ""));
                                bool success = true;
                                IEnumerator schemata = schemaTest.EnumerateAxis(XdmAxis.Child, schemaDocumentNT);
                                while (schemata.MoveNext()) {
                                    XdmNode schemaDocumentRef = (XdmNode)schemata.Current;
                                    if (schemaDocumentRef == null) {
                                        break;
                                    }
                                    Console.WriteLine("Loading schema at " + schemaDocumentRef.GetAttributeValue(xlinkHref));
                                    XdmNode schemaDoc = getLinkedDocument(schemaDocumentRef, testConfig, false);
                                    IEnumerator schemaDocKids = schemaDoc.EnumerateAxis(XdmAxis.Child);
                                    XdmNode schemaElement = null;
                                    while (schemaDocKids.MoveNext())
                                    {
                                        schemaElement = (XdmNode)schemaDocKids.Current;
                                        if (schemaElement.NodeKind == XmlNodeType.Element)
                                        {
                                            break;
                                        }
                                    }
                                    String targetNamespace = schemaElement.GetAttributeValue(targetNamespaceAtt);
                                    //if (targetNamespace != null && schemaManager. isSchemaAvailable(targetNamespace)) {
                                        // do nothing
                                        // TODO: this is the only way I can get MS additional test addB132 to work.
                                        // It's not ideal: addSchemaSource() ought to be a no-op if the schema components
                                        // are already loaded, but in fact recompiling the imported schema document on its
                                        // own is losing the substitution group membership that was defined in the
                                        // importing document.
                                    //} else {
                                    IList errorList = new ArrayList();
                                    schemaManager.ErrorList = errorList;
                                    try
                                    {
                                        schemaManager.Compile(schemaDoc);
                                    }
                                    catch (Exception e)
                                    {
                                        if (errorList.Count == 0)
                                        {
                                            feedback.Message("In " + testName + ", exception thrown but no errors in ErrorList\n", true);
                                            results.Write("<!--" + e.Message + "-->");
                                            success = false;
                                        }
                                    }
                                    for (int i = 0; i < errorList.Count; i++)
                                    {
                                        if (errorList[i] is StaticError)
                                        {
                                            StaticError err = (StaticError)errorList[i];
                                            if (!err.IsWarning)
                                            {
                                                success = false;
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            feedback.Message("In " + testName + " wrong kind of error!" + errorList[i].GetType() + "\n", true);
                                        }
                                    }
                                }
                                XdmNode expected = getChildElement(schemaTest, expectedNT);
                                bool expectedSuccess = expected==null ||
                                        expected.GetAttributeValue(validityAtt) == "valid";
                                if (success == expectedSuccess)
                                {
                                    passed++;
                                }
                                else
                                {
                                    failed++;
                                }
                                feedback.Feedback(passed, failed, total);
                                results.Write("<testResult set='" + testSetName +
                                        "' group='" + testGroupName +
                                        "' test='" + testName +
                                        "' validity='" + (success ? "valid" : "invalid" ) +
                                        (queried ? "' saxon:queried='true' saxon:bugzilla='" + bugzillaRef : "") +
                                        "' saxon:outcome='" + (success==expectedSuccess ? "same" : "different") +
                                        "'/>\n");
                            }
                            IEnumerator instanceTests = testGroup.EnumerateAxis(XdmAxis.Child, instanceTestNT);
                            while (instanceTests.MoveNext()) {
                                XdmNode instanceTest = (XdmNode)instanceTests.Current;
                                String testName = instanceTest.GetAttributeValue(nameAtt);

                                if (exception != null) {
                                    results.Write("<testResult set='" + testSetName +
                                            "' group='" + testGroupName +
                                            "' test='" + testName +
                                            "' validity='notKnown' saxon:outcome='notRun' saxon:comment='" + exception +
                                            "'/>\n");
                                    continue;
                                }

                                bool queried = false;
                                XdmNode statusElement = getChildElement(instanceTest, currentNT);
                                if (statusElement != null) {
                                    String status = statusElement.GetAttributeValue(statusAtt);
                                    queried = ("queried" == status);
                                    String instanceBug = statusElement.GetAttributeValue(bugzillaAtt);
                                    if (instanceBug != null) {
                                        bugzillaRef = instanceBug;
                                    }
                                }
                                queried |= schemaQueried;

                                Console.WriteLine("TEST INSTANCE " + testName + (queried ? " (queried)" : ""));

                                XdmNode instanceDocument = getChildElement(instanceTest, instanceDocumentNT);

                                bool success = true;
                                try
                                {
                                    XdmNode instanceDoc = getLinkedDocument(instanceDocument, testConfig, true);
                                }
                                catch (Exception)
                                {
                                    success = false;
                                }
                                
                                XdmNode expected = getChildElement(instanceTest, expectedNT);
                                bool expectedSuccess = expected==null ||
                                        expected.GetAttributeValue(validityAtt) == "valid";
                                if (success == expectedSuccess)
                                {
                                    passed++;
                                }
                                else
                                {
                                    failed++;
                                }
                                feedback.Feedback(passed, failed, total);
                                results.Write("<testResult set='" + testSetName +
                                        "' group='" + testGroupName +
                                        "' test='" + testName +
                                        "' validity='" + (success ? "valid" : "invalid" ) +
                                        (queried ? "' saxon:queried='true' saxon:bugzilla='" + bugzillaRef : "") +
                                        "' saxon:outcome='" + (success==expectedSuccess ? "same" : "different") +
                                        "'/>\n");

                            }
                        }
                    }

                    results.Write("</testSuiteResults>");
                    results.Close();

                } catch (Exception e) {
                    feedback.Message("Test failed: " + e.Message, true);
                }
            }
Exemple #24
0
        // internal constructor: the public interface is a factory method
        // on the Processor object

        internal XPathCompiler(Processor processor, JXPathCompiler compiler)
        {
            this.compiler  = compiler;
            this.processor = processor;
        }
Exemple #25
0
        protected void Application_Start(object sender, EventArgs e)
        {
            //System.Web.HttpApplication application = (System.Web.HttpApplication)sender;

            m_useMemCached = false;
            m_DEBUG = false;
            m_memcachedClient = null;
            m_appSettings = new AppSettings();
            m_xameleonConfiguration = AspNetXameleonConfiguration.GetConfig();
            string hashkey = (string)m_xameleonConfiguration.ObjectHashKey;
            Application["hashkey"] = hashkey;
            m_awsConfiguration = AspNetAwsConfiguration.GetConfig();
            m_transform = new Transform.Transform();
            m_processor = new Processor();
            m_serializer = new Serializer();
            m_resolver = new XmlUrlResolver();
            m_namedXsltHashtable = new Hashtable();
            m_globalXsltParams = new Hashtable();
            m_transformContextHashtable = new Hashtable();
            m_xmlServiceOperationManager = new XPathServiceOperationManager(new Dictionary<int, XPathNavigator>());
            m_geoIPLookup = new Dictionary<String, IPLocation>();
            m_requestXsltParams = null;
            m_encoding = new UTF8Encoding();
            m_pledgeCount = new PledgeCount(0, 0);
            m_pledgeQueue = new Queue<string>();

            string sdbAccessKey = String.Empty;
            string sdbSecretKey = String.Empty;
            string awsUriEndpoint = "https://sdb.amazonaws.com/";

            Environment.SetEnvironmentVariable("AWS_URI_ENDPOINT", awsUriEndpoint);
            

            using (XmlReader configReader = XmlReader.Create(HttpContext.Current.Server.MapPath("~/App_Config/aws.config")))
            {
                while (configReader.Read())
                {
                    if (configReader.IsStartElement())
                    {
                        switch (configReader.Name)
                        {
                            case "sdb-access-key":
                                {
                                    sdbAccessKey = configReader.ReadString();
                                    Environment.SetEnvironmentVariable("AWS_PUBLIC_KEY", sdbAccessKey);
                                    Console.WriteLine("SDB_ACCESS_KEY: {0}", sdbAccessKey);
                                    break;
                                }
                            case "sdb-secret-key":
                                {
                                    sdbSecretKey = configReader.ReadString();
                                    Environment.SetEnvironmentVariable("AWS_PRIVATE_KEY", sdbSecretKey);
                                    Console.WriteLine("SDB_PRIVATE_KEY: {0}", sdbSecretKey);
                                    break;
                                }
                            default:
                                break;
                        }
                    }
                }
            }

            if (m_xameleonConfiguration.DebugMode == "yes")
                m_DEBUG = true;

            if (m_xameleonConfiguration.UseMemcached == "yes")
            {
                m_useMemCached = true;
                m_memcachedClient = new Client(new MemcachedClient(), AspNetMemcachedConfiguration.GetConfig());
            }

            string baseUri = (string)m_xameleonConfiguration.PreCompiledXslt.BaseUri;
            if (baseUri != String.Empty)
                baseUri = (string)m_xameleonConfiguration.PreCompiledXslt.BaseUri;
            else
                baseUri = "~";

            m_xsltTransformationManager = new XsltTransformationManager(m_processor, m_transform, m_resolver, m_serializer);
            m_xsltTransformationManager.HashAlgorithm = m_hashAlgorithm;
            m_resolver.Credentials = CredentialCache.DefaultCredentials;
            m_namedXsltHashtable = m_xsltTransformationManager.NamedXsltHashtable;

            foreach (PreCompiledXslt xslt in m_xameleonConfiguration.PreCompiledXslt)
            {
                string localBaseUri = (string)m_xameleonConfiguration.PreCompiledXslt.BaseUri;
                if (localBaseUri == String.Empty)
                    localBaseUri = baseUri;
                Uri xsltUri = new Uri(HttpContext.Current.Server.MapPath(localBaseUri + xslt.Uri));
                m_xsltTransformationManager.Compiler.BaseUri = xsltUri;
                m_xsltTransformationManager.AddTransformer(xslt.Name, xsltUri, m_resolver, xslt.InitialMode, xslt.InitialTemplate);
                m_namedXsltHashtable.Add(xslt.Name, xsltUri);
                if (xslt.UseAsBaseXslt == "yes")
                {
                    m_baseXsltContext = new BaseXsltContext(xsltUri, XsltTransformationManager.GenerateNamedETagKey(xslt.Name, xsltUri), xslt.Name);
                }
            }

            m_xsltTransformationManager.SetBaseXsltContext(m_baseXsltContext);

            foreach (XsltParam xsltParam in m_xameleonConfiguration.GlobalXsltParam)
            {
                m_globalXsltParams[xsltParam.Name] = (string)xsltParam.Select;
            }

            if (m_memcachedClient != null)
                Application["as_memcached"] = m_memcachedClient;
            Application["as_usememcached"] = m_useMemCached;
            Application["as_xslTransformationManager"] = m_xsltTransformationManager;
            Application["as_xmlServiceOperationManager"] = m_xmlServiceOperationManager;
            Application["as_namedXsltHashtable"] = m_namedXsltHashtable;
            Application["as_globalXsltParams"] = m_globalXsltParams;
            Application["as_geoIPLookup"] = m_geoIPLookup;
            Application["as_debug"] = m_DEBUG;
            Application["as_hashkey"] = hashkey;
            Application["as_encoding"] = m_encoding;
            Application["as_pledgeCount"] = m_pledgeCount;
            Application["as_pledgeQueue"] = m_pledgeQueue;
        }
Exemple #26
0
        // internal constructor

        internal SchemaValidator(JSchemaValidator validator, Processor processor)
        {
            this.processor = processor;
            this.schemaValidator = validator;
            this.config = processor.Implementation;
        }
 public XsltTransformationManager (Processor processor, Transform transform, XmlUrlResolver resolver, Serializer serializer)
     : this(processor, transform, resolver, serializer, new Dictionary<string, XsltTransformer>(), new Hashtable(), new Hashtable(), new Hashtable(), new Hashtable(), new Hashtable(), null, null, null) {
 }
Exemple #28
0
 internal DocumentBuilder(Processor processor)
 {
     this.processor   = processor;
     this.config      = processor.Implementation;
     this.xmlResolver = new XmlUrlResolver();
 }
Exemple #29
0
        /// <summary>
        /// Show a query producing a Saxon tree as its input and producing a Saxon tree as its output
        /// </summary>
        public override void run(Uri samplesDir)
        {
            Processor processor = new Processor();

            DocumentBuilder loader = processor.NewDocumentBuilder();
            loader.BaseUri = new Uri(samplesDir, "data/books.xml");
            XdmNode indoc = loader.Build(loader.BaseUri);

            XQueryCompiler compiler = processor.NewXQueryCompiler();
            XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>");
            XQueryEvaluator eval = exp.Load();
            eval.ContextItem = indoc;
            XdmDestination qout = new XdmDestination();
            eval.Run(qout);
            XdmNode outdoc = qout.XdmNode;
            Console.WriteLine(outdoc.OuterXml);
        }
Exemple #30
0
 /// <summary>
 /// Show a query producing a document as its result and serializing this to a FileStream
 /// </summary>
 public override void run(Uri samplesDir)
 {
     Processor processor = new Processor();
     XQueryCompiler compiler = processor.NewXQueryCompiler();
     compiler.BaseUri = samplesDir.ToString();
     compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");
     XQueryExecutable exp = compiler.Compile("<saxon:example>{static-base-uri()}</saxon:example>");
     XQueryEvaluator eval = exp.Load();
     Serializer qout = new Serializer();
     qout.SetOutputProperty(Serializer.METHOD, "xml");
     qout.SetOutputProperty(Serializer.INDENT, "yes");
     qout.SetOutputProperty(Serializer.SAXON_INDENT_SPACES, "1");
     qout.SetOutputStream(new FileStream("testoutput.xml", FileMode.Create, FileAccess.Write));
     Console.WriteLine("Output written to testoutput.xml");
     eval.Run(qout);
 }
Exemple #31
0
        /// <summary>
        /// Show a query producing a sequence as its result and returning the sequence
        /// to the C# application in the form of an iterator. The sequence is then
        /// output by serializing each item individually, with each item on a new line.
        /// </summary>
        public override void run(Uri samplesDir)
        {
            Processor processor = new Processor();
            String inputFileName = new Uri(samplesDir, "data/books.xml").ToString();
            //XmlTextReader reader = new XmlTextReader(inputFileName,
            //    new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
            XmlTextReader reader = new XmlTextReader(inputFileName,
                UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")));
            reader.Normalization = true;

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

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

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

            foreach (XdmNode node in eval)
            {
                Console.WriteLine(node.OuterXml);
            }
        }
 internal DocumentBuilder(Processor processor) {
     this.processor = processor;
     this.config = processor.Implementation;
 }
Exemple #33
0
 /**
  * <summary>Set the Processor associated with this Serializer. This will be called automatically if the
  * serializer is created using one of the <c>Processor.NewSerializer()</c> methods.</summary>
  *
  * <param name="processor"> processor the associated Processor</param>
  */
 public void SetProcessor(Processor processor)
 {
     this.config = processor.config;
 }
Exemple #34
-22
 private static XmlDocument Process (XmlReader funcSeq, XmlReader extTransform, Uri baseUri) {
   Processor processor = new Processor();
   XdmNode input = processor.NewDocumentBuilder().Build(funcSeq);
   XsltCompiler compiler = processor.NewXsltCompiler();
   compiler.BaseUri = baseUri;
   XsltTransformer transformer = compiler.Compile(extTransform).Load();
   transformer.InitialContextNode = input;
   DomDestination result = new DomDestination();
   transformer.Run(result);
   return result.XmlDocument;
 }