Example #1
5
        /// <summary>
        /// Processes the record.
        /// </summary>
        protected override void ProcessRecord()
        {
            this.WriteVerbose("Formatting log");
            using (var xmlReader = new StringReader(this.Log))
            {
                var xpath = new XPathDocument(xmlReader);
                using (var writer = new StringWriter())
                {
                    var transform = new XslCompiledTransform();
                    Func<string, string> selector = file => !Path.IsPathRooted(file) ? Path.Combine(Environment.CurrentDirectory, file) : file;
                    foreach (var fileToLoad in this.FormatFile.Select(selector))
                    {
                        this.WriteVerbose("Loading format file " + fileToLoad);
                        using (var stream = File.OpenRead(fileToLoad))
                        {
                            using (var reader = XmlReader.Create(stream))
                            {
                                transform.Load(reader);
                                transform.Transform(xpath, null, writer);
                            }
                        }
                    }

                    this.WriteObject(writer.GetStringBuilder().ToString(), false);
                }
            }
        }
Example #2
0
        public void ShouldAllowAnXsltToBeRunSuccessfully()
        {
            string xhtmlPage = "http://localhost/webdriver/xhtmlTest.html";
            driver.Get(xhtmlPage);

            XPathNavigator navigator = driver.CreateNavigator();
            XmlDocument xslDoc = new XmlDocument();
            xslDoc.LoadXml(
              @"<?xml version=""1.0""?>
                <xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">
                    <xsl:template match=""/"">
                        <xsl:copy-of select="".""/>
                    </xsl:template>
                </xsl:stylesheet>");

            XslCompiledTransform xsl = new XslCompiledTransform();
            xsl.Load(xslDoc);

            StringBuilder output = new StringBuilder();
            xsl.Transform(navigator, new XsltArgumentList(), new StringWriter(output));

            String result = output.ToString();

            // Do we get text in the body of the transformed document?
            Assert.IsTrue(result.Contains("XHTML Might Be The Future"), "No text from the body of the page");

            // Do we get tag's?
            Assert.IsTrue(result.Contains("<"), "No tags appear to have been opened");
            Assert.IsTrue(result.Contains("</body"), "The body tag has not been closed. Check that tags are being output");

            // Do we get the page's title?
            Assert.IsTrue(result.Contains("XHTML Test Page"), "No title seen");
        }
Example #3
0
 public static void Main()
 {
     XslCompiledTransform styleSheet = new XslCompiledTransform();
     styleSheet.Load("../../style.xslt");
     styleSheet.Transform("../../catalogue.xml", "../../catalogue.html");
     Console.WriteLine("Please open project folder to see the result");
 }
        /// <summary>
        /// Perform the xml translation
        /// </summary>
        /// <param name="xmlRaw"></param>
        /// <param name="xslSheet"></param>
        /// <returns></returns>
        public static XmlDocument TransformXml(XmlDocument xmlRawClean, XslCompiledTransform xslSheet)
        {
            XmlDocument xmlTransform = null;
            XmlTextWriter xmlWriter = null;

            try
            {
                XPathDocument xmlClean = ConvertXmlDocumentToXPathDocument(xmlRawClean);

                string sTempPath = FileUtilities.GetUniqueTempFileName();
                xmlWriter = new XmlTextWriter(sTempPath, null);
                xslSheet.Transform(xmlClean, null, xmlWriter);
                xmlWriter.Close();

                xmlTransform = new XmlDocument();
                xmlTransform.Load(sTempPath);

                // try to clean up the file we created
                try
                {
                    File.Delete(sTempPath);
                }
                catch
                {

                }
            }
            catch (Exception ex)
            {
                throw new Exception("TransformXml", ex.InnerException);
            }

            return xmlTransform;
        }
        public string GetHtml(string transform_path, string xml)
        {
            string xsltPath = Server.MapPath(transform_path) + "\\sdctemplate.xslt";
            string csspath  = Server.MapPath(transform_path) + "\\sdctemplate.css";

            //3/10/2016 - change encoding to unicode
            System.IO.MemoryStream              stream    = new System.IO.MemoryStream(System.Text.UnicodeEncoding.ASCII.GetBytes(xml));
            System.Xml.XPath.XPathDocument      document  = new System.Xml.XPath.XPathDocument(stream);
            System.IO.StringWriter              writer    = new System.IO.StringWriter();
            System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();

            System.Xml.Xsl.XsltSettings settings = new System.Xml.Xsl.XsltSettings(true, true);

            System.Xml.XmlSecureResolver resolver = new System.Xml.XmlSecureResolver(new System.Xml.XmlUrlResolver(), csspath);
            try
            {
                transform.Load(xsltPath, settings, resolver);
                transform.Transform(document, null, writer);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(writer.ToString());
        }
        public static string Transform (string xml, XslCompiledTransform xslTrans, IDictionary<string, string> xslParams)
        {
            if (xml.Trim ().Length == 0)
                return String.Empty;

            XmlDocument xmlDoc = new XmlDocument ();
            xmlDoc.LoadXml (xml);

            XsltArgumentList xslArgs = null;

            if (xslParams != null)
            {
                xslArgs = new XsltArgumentList ();

                foreach (string paramName in xslParams.Keys)
                {
                    xslArgs.AddParam (paramName, "", xslParams [paramName]);
                }
            }

            using (StringWriter sw = new StringWriter())
            {
                xslTrans.Transform(xmlDoc, xslArgs, sw);
                return sw.ToString();
            }
        }
        public static String TransformXml(XmlTextReader xsltReader, XmlTextReader xmlReader)
        {
            // Create required writer for output
            StringWriter stringWriter = new StringWriter();
            XmlTextWriter transformedXml = new XmlTextWriter(stringWriter);

            // Create a XslCompiledTransform to perform transformation
            XslCompiledTransform xsltTransform = new XslCompiledTransform();

            try
            {
                xsltTransform.Load(xsltReader);
                xsltTransform.Transform(xmlReader, new XsltArgumentList(), transformedXml);
            }
            catch (XmlException xmlEx)
            {
                // TODO : log - "Could not load XSL transform: \n\n" + xmlEx.Message
                throw;
            }
            catch (XsltException xsltEx)
            {
                // TODO : log - "Could not process the XSL: \n\n" + xsltEx.Message + "\nOn line " + xsltEx.LineNumber + " @ " + xsltEx.LinePosition)
                throw;
            }
            catch (Exception ex)
            {
                // TODO : log
                throw;
            }

            return stringWriter.ToString();
        }
        public void Transform()
        {
            var xsltTemplateReader = new XmlTextReader(_xsltPath);
            var emptyDocumentReader = XmlReader.Create(new System.IO.StringReader("<empty />"));

            var settings = new XmlWriterSettings();
            //settings.ConformanceLevel = ConformanceLevel.Fragment;
            settings.Indent = true;

            using (var outputWriter = XmlWriter.Create(_outputPath, settings))
            {
                var xsltSettings = new XsltSettings();

                XsltArgumentList argumentList = new XsltArgumentList();

                var extensions = new XsltExtensionMethods(_settings);

                argumentList.AddExtensionObject("http://core.com/config", extensions);
                argumentList.AddExtensionObject("http://paralect.com/config", extensions);

                var transformer = new XslCompiledTransform(true);
                transformer.Load(xsltTemplateReader, xsltSettings, null);
                transformer.Transform(emptyDocumentReader,argumentList, outputWriter);
            }
        }
        public string TransformClaimDocumentToFoXml(ClaimDocument document)
        {
            FormDocument form = new FormDocument();

            foreach (var claim in document.Claims)
            {
                if (claim.Type == ClaimTypeEnum.Professional)
                {
                    var pages = _professionalTransformation.TransformClaimToClaimFormFoXml(claim);
                    form.Pages.AddRange(pages);
                }
                else if (claim.Type == ClaimTypeEnum.Institutional)
                {
                    var pages = _institutionalTransformation.TransformClaimToClaimFormFoXml(claim);
                    form.Pages.AddRange(pages);
                }
                else
                    form.Pages.AddRange(_dentalTransformation.TransformClaimToClaimFormFoXml(claim));
            }

            var xml = form.Serialize();

            var transformStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("OopFactory.X12.Hipaa.Claims.Services.Xsl.FormDocument-To-FoXml.xslt");

            var transform = new XslCompiledTransform();
            if (transformStream != null) transform.Load(XmlReader.Create(transformStream));

            var outputStream = new MemoryStream();

            transform.Transform(XmlReader.Create(new StringReader(xml)), new XsltArgumentList(), outputStream);
            outputStream.Position = 0;
            return new StreamReader(outputStream).ReadToEnd();
        }
        private void DrawProfilesModule()
        {
            XsltArgumentList args = new XsltArgumentList();
            XslCompiledTransform xslt = new XslCompiledTransform();
            SessionManagement sm = new SessionManagement();

            Utilities.DataIO data = new Profiles.Profile.Utilities.DataIO();
            string email = string.Empty;
            string imageemailurl = string.Empty;
            if (this.BaseData.SelectSingleNode("rdf:RDF[1]/rdf:Description[1]/prns:emailEncrypted", this.Namespaces) != null &&
                this.BaseData.SelectSingleNode("rdf:RDF[1]/rdf:Description[1]/vivo:email", this.Namespaces) == null)
            {
                email = this.BaseData.SelectSingleNode("rdf:RDF[1]/rdf:Description[1]/prns:emailEncrypted", this.Namespaces).InnerText;
                imageemailurl = string.Format(Root.Domain + "/profile/modules/CustomViewPersonGeneralInfo/" + "EmailHandler.ashx?msg={0}", HttpUtility.UrlEncode(email));
            }

            args.AddParam("root", "", Root.Domain);
            if (email != string.Empty)
            {
                args.AddParam("email", "", imageemailurl);
            }
            args.AddParam("imgguid", "", Guid.NewGuid().ToString());

            litPersonalInfo.Text = XslHelper.TransformInMemory(Server.MapPath("~/Profile/Modules/CustomViewPersonGeneralInfo/CustomViewPersonGeneralInfo.xslt"), args, base.BaseData.OuterXml);

            if (base.BaseData.SelectSingleNode("rdf:RDF/rdf:Description[1]/prns:mainImage/@rdf:resource", base.Namespaces) != null)
            {
                string imageurl = base.BaseData.SelectSingleNode("//rdf:RDF/rdf:Description[1]/prns:mainImage/@rdf:resource", base.Namespaces).Value;
                imgPhoto.ImageUrl = imageurl + "&cachekey=" + Guid.NewGuid().ToString();
            }
            else
            {
                imgPhoto.Visible = false;
            }
        }
Example #11
0
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("You have not entered the correct parameters");
                return;
            }

            string xmlfile = args[0];
            string xslfile = args[1];
            string outfile = args[2];

            try
            {
                var doc = new XPathDocument(xmlfile);
                var transform = new XslCompiledTransform();
                var settings = new XsltSettings(true, true);
                transform.Load(xslfile, settings, new XmlUrlResolver());
                var writer = new XmlTextWriter(outfile, null);
                transform.Transform(doc, null, writer);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
Example #12
0
    protected void Store1_Submit(object sender, StoreSubmitDataEventArgs e)
    {
        try
        {
            var json    = FormatType.Value.ToString();
            var eSubmit = new StoreSubmitDataEventArgs(json, null);
            var xml     = eSubmit.Xml;

            if (xml.InnerText == "")
            {
                X.Msg.Alert("Thông báo", "Không có dữ liệu để xuất ra file Excel").Show();
                return;
            }
            Response.Clear();

            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", "attachment; filename=Export_Tieu_Chi_Danh_Gia.xls");
            var xtExcel = new System.Xml.Xsl.XslCompiledTransform();
            xtExcel.Load(Server.MapPath("../Export/Excel.xsl"));

            xtExcel.Transform(xml, null, Response.OutputStream);
            Response.End();
        }
        catch (Exception ex)
        {
            X.Msg.Alert("Thông báo", "Có lỗi xảy ra: " + ex.Message.ToString()).Show();
        }
    }
        public static string Transform (string xml, string xslFile, IDictionary<string, string> xslParams)
        {
            XslCompiledTransform xslTrans = new XslCompiledTransform ();
            xslTrans.Load (xslFile);

            return Transform (xml, xslTrans, xslParams);
        }
Example #14
0
        public static string ApplyXslt(this string xml, string xslt, ISubstitutionContext context, Func <string, string> processIncludes = null)
        {
            var temp = Path.GetTempFileName();
            var res  = new StringBuilder();

            try
            {
                var c = new System.Xml.Xsl.XslCompiledTransform(true);
                File.WriteAllText(temp, xslt);
                c.Load(temp, new XsltSettings(true, true), new Resolver(context, temp, processIncludes));

                using (var xmlreader = XmlReader.Create(new StringReader(xml)))
                {
                    using (var resultWriter = XmlWriter.Create(new StringWriter(res), new XmlWriterSettings()
                    {
                        ConformanceLevel = ConformanceLevel.Fragment
                    }))
                    {
                        c.Transform(xmlreader, resultWriter);
                    }
                }
            }
            finally
            {
                try { File.Delete(temp); }
                catch { }
            }
            return(res.ToString());
        }
Example #15
0
        static int Main(string[] args)
        {
            Console.WriteLine("XMLTo v0.1 [www.mosa-project.org]");
            Console.WriteLine("Copyright 2009 by the MOSA Project. Licensed under the New BSD License.");
            Console.WriteLine("Written by Philipp Garcia ([email protected])");
            Console.WriteLine();
            Console.WriteLine("Usage: XMLTo <xml file> <xsl file> <output file>");
            Console.WriteLine();

            if (args.Length < 3)
             {
                Console.Error.WriteLine("ERROR: Missing arguments");
                return -1;
            }

            try {
                XPathDocument myXPathDoc = new XPathDocument(args[0]);
                XslCompiledTransform myXslTrans = new XslCompiledTransform();
                myXslTrans.Load(args[1]);
                XmlTextWriter myWriter = new XmlTextWriter(args[2], null);
                myXslTrans.Transform(myXPathDoc, null, myWriter);

                return 0;
            }
            catch (Exception e) {
                Console.Error.WriteLine("Exception: {0}", e.ToString());
                return -1;
            }
        }
Example #16
0
		static int Main (string [] args)
		{
			if (args.Length != 2) {
				Console.WriteLine ("Usage: mono gen-apidiff-html.exe <diff_dir> <html_file>");
				return 1;
			}

			string diff_dir = args[0];
			string out_file = args[1];

			var all = new XmlDocument ();
			all.AppendChild(all.CreateElement ("assemblies"));
			foreach (string file in Directory.EnumerateFiles(diff_dir, "*.apidiff")) {
				Console.WriteLine ("Merging " + file);
				var doc = new XmlDocument ();
				doc.Load (file);
				foreach (XmlNode child in doc.GetElementsByTagName ("assembly")) {
					XmlNode imported = all.ImportNode (child, true);
					all.DocumentElement.AppendChild (imported);
				}
			}

			var transform = new XslCompiledTransform ();
			transform.Load ("mono-api.xsl");
			var writer = new StreamWriter (out_file);

			Console.WriteLine (String.Format ("Transforming to {0}...", out_file));
			transform.Transform (all.CreateNavigator (), null, writer);
			writer.Close ();

			return 0;
		}
Example #17
0
 public static void Main()
 {
     XslCompiledTransform xsltStyle = new XslCompiledTransform();
     xsltStyle.Load("../../catalogstyle.xslt");
     xsltStyle.Transform("../../catalog.xml", "../../catalog.html");
     Console.WriteLine("catalog.html created");
 }
        private static StringBuilder Transform(string gcmlPath)
        {
            if(!File.Exists(gcmlPath))
            {
                throw new GCMLFileNotFoundException("The GCML File" + gcmlPath + " does not exist.");
            }

            if(!File.Exists(xsltFilePath))
            {
                throw new XSLTFileNotFoundException("The XSLT File" + xsltFilePath + " does not exist.");
            }

            StringBuilder sb = new StringBuilder();
            XmlTextReader xmlSource = new XmlTextReader(gcmlPath);
            XPathDocument xpathDoc = new XPathDocument(xmlSource);
            XslCompiledTransform xsltDoc = new XslCompiledTransform();

            xsltDoc.Load(xsltFilePath);

            StringWriter sw = new StringWriter(sb);
            try
            {
                xsltDoc.Transform(xpathDoc, null, sw);
            }
            catch (XsltException except)
            {
                Console.WriteLine(except.Message);
                throw except;
            }

            return sb;
        }
Example #19
0
        public HxS(string workingDir, string hxsFile,
            string title, string copyright, string locale,
            TreeNodeCollection nodes,
            Content contentDataSet,
            Dictionary<string, string> links)
        {
            this.locale = locale;
            this.title = title;
            this.copyright = copyright;
            this.nodes = nodes;
            this.contentDataSet = contentDataSet;
            this.links = links;

            this.outputFile = Path.GetFullPath(hxsFile);
            this.rawDir = Path.Combine(workingDir, "raw");

            // The source shouldn't be hidden away. If an error happens (likely) the user needs to check logs etc.
            //this.hxsDir = Path.Combine(workingDir, "hxs");
            this.hxsDir = GetUniqueDir(hxsFile);
            this.withinHxsDir = Path.Combine(hxsDir, hxsSubDir);
            this.baseFilename = Path.GetFileNameWithoutExtension(hxsFile);
            this.baseFilename = this.baseFilename.Replace(" ", "_");  //replace spaces with _ otherwise we get compile errors

            this.logFile = Path.Combine(hxsDir, this.baseFilename + ".log");
            this.projectFile = Path.Combine(hxsDir, baseFilename + ".hxc");

            if (xform == null)
            {
                xform = new XslCompiledTransform(true);
                xform.Load(transformFile);
            }
        }
Example #20
0
        public string Transform(String xml, String xsltPath)
        {
            string result = String.Empty;

            string pathxsl = Path.Combine(DirectoryUtil.AssemblyDirectory, xsltPath);

            System.Xml.Xsl.XslCompiledTransform transformador = new System.Xml.Xsl.XslCompiledTransform(true);
            transformador.Load(pathxsl);

            using (StringReader sri = new StringReader(xml)) // xmlInput is a string that contains xml
            {
                using (XmlReader xri = XmlReader.Create(sri))
                {
                    using (StringWriter sw = new StringWriter())
                    {
                        using (XmlWriter xwo = XmlWriter.Create(sw, transformador.OutputSettings))
                        {
                            transformador.Transform(xri, xwo);
                            result = sw.ToString();
                        }
                    }
                }
            }

            return(result);
        }
Example #21
0
 /// <summary>
 /// Creates a new SPARQL XSLT Writer
 /// </summary>
 /// <param name="stylesheetUri">Stylesheet URI</param>
 public SparqlXsltWriter(String stylesheetUri)
 {
     //Load the Transform
     this._transform = new XslCompiledTransform();
     XsltSettings settings = new XsltSettings();
     this._transform.Load(stylesheetUri, settings, null);
 }
Example #22
0
        private void TransformXml()
        {
            XslCompiledTransform xslTransformer = new XslCompiledTransform();
            xslTransformer.Load( Server.MapPath( AttributeValue("XSLTFile") ) );

            Rock.Web.Cache.Page rootPage;
            if ( AttributeValue( ROOT_PAGE ) != string.Empty )
            {
                int pageId = Convert.ToInt32( AttributeValue( ROOT_PAGE ) );
                if ( pageId == -1 )
                    rootPage = PageInstance;
                else
                    rootPage = Rock.Web.Cache.Page.Read( pageId );
            }
            else
                rootPage = PageInstance;

            int levelsDeep = Convert.ToInt32( AttributeValue( NUM_LEVELS ) );

            XDocument pageXml = rootPage.MenuXml( levelsDeep, CurrentUser );

            StringBuilder sb = new StringBuilder();
            TextWriter tw = new StringWriter( sb );
            xslTransformer.Transform( pageXml.CreateReader(), null, tw );

            phContent.Controls.Clear();
            phContent.Controls.Add( new LiteralControl( sb.ToString() ) );
        }
Example #23
0
 public static void XSLTransform(XmlDocument doc, ref StreamWriter writer, string xsltUrl)
 {
     System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform();
     xslt.Load(xsltUrl);
     //Transform the file.
     xslt.Transform(doc, null, writer);
 }
Example #24
0
    private void Transform_Results(string xsltResourceName, XElement element, XmlWriter writer)
    {
        var xmlTransform = new System.Xml.Xsl.XslCompiledTransform();
        var name         = GetType().Assembly.GetManifestResourceNames().Where(a => a.EndsWith(xsltResourceName, StringComparison.Ordinal)).FirstOrDefault();

        if (name == null)
        {
            return;
        }

        using (var xsltStream = GetType().Assembly.GetManifestResourceStream(name))
        {
            if (xsltStream == null)
            {
                throw new Exception($"Stream with name {name} cannot be found! We have {GetType().Assembly.GetManifestResourceNames()[0]}");
            }
            // add the extension so that we can get the hash from the name of the test
            // Create an XsltArgumentList.
            var xslArg = new XsltArgumentList();

            var generator = new XsltIdGenerator();
            xslArg.AddExtensionObject("urn:hash-generator", generator);

            using (var xsltReader = XmlReader.Create(xsltStream))
                using (var xmlReader = element.CreateReader())
                {
                    xmlTransform.Load(xsltReader);
                    xmlTransform.Transform(xmlReader, xslArg, writer);
                }
        }
    }
Example #25
0
        public static string Transform(string xml, string xslPath)
        {
            try
            {
                //create an XPathDocument using the reader containing the XML
                MemoryStream m = new MemoryStream(System.Text.Encoding.Default.GetBytes(xml));

                XPathDocument xpathDoc = new XPathDocument(new StreamReader(m));

                //Create the new transform object
                XslCompiledTransform transform = new XslCompiledTransform();

                //String to store the resulting transformed XML
                StringBuilder resultString = new StringBuilder();

                XmlWriter writer = XmlWriter.Create(resultString);

                transform.Load(xslPath);

                transform.Transform(xpathDoc,writer);
               
                return resultString.ToString();
            }
            catch (Exception e)
            {

                Console.WriteLine("Exception: {0}", e.ToString());
                return e.ToString();
            }
        }
		public string GetSearchResultsHtml(string term, int skip, int take)
		{
			var response = new StringBuilder();

			var xmlResults = this.SearchData.GetSearchResultsXML(term, skip, take);

			if (xmlResults != null)
			{
				using (var xmlReader = XmlReader.Create(new StringReader(xmlResults.OuterXml)))
				{
					using (var xslReader = XmlReader.Create(HttpContext.Current.Server.MapPath(XSLTTransformFile)))
					{
						using (var xmlWriter = XmlWriter.Create(response, new XmlWriterSettings
						{
							OmitXmlDeclaration = true
						}))
						{
							var xslTransformer = new XslCompiledTransform();

							xslTransformer.Load(xslReader, new XsltSettings(true, true), new XmlUrlResolver
							{
								Credentials = CredentialCache.DefaultCredentials
							});

							xslTransformer.Transform(xmlReader, xmlWriter);
						}
					}
				}
			}

			return response.ToString();
		}
		protected static void MigrateUsingXslt(TextReader xslStream, TextReader xmlStream, string destinationFilePath)
		{
			var transform = new XslCompiledTransform();
			using (xslStream)
			{
				using (xmlStream)
				{
					using (var destinationStream = new StreamWriter(destinationFilePath))
					{
						var xslReader = XmlReader.Create(xslStream);
						transform.Load(xslReader);
						xslReader.Close();
						xslStream.Close();

						var reader = XmlReader.Create(xmlStream);

						var settings = new XmlWriterSettings { Indent = true };
						var writer = XmlWriter.Create(destinationStream, settings);

						transform.Transform(reader, writer);

						var tempfiles = transform.TemporaryFiles;
						if (tempfiles != null) // tempfiles will be null when debugging is not enabled
						{
							tempfiles.Delete();
						}
						writer.Close();
						reader.Close();
						destinationStream.Close();
					}
					xmlStream.Close();
				}
			}
		}
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            if (!request.IsEmpty)
            {
                XmlReader bodyReader = request.GetReaderAtBodyContents().ReadSubtree();

                MemoryStream stream = new MemoryStream();
                XmlWriter writer = XmlWriter.Create(stream);

                if (transform == null)
                {
                    transform = new XslCompiledTransform(true);
                    var reader = XmlReader.Create(new StringReader(Properties.Resources.XmlCleaner));
                    transform.Load(reader);
                }
                transform.Transform(bodyReader, writer);

                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);

                bodyReader = XmlReader.Create(stream);

                Message changedMessage = Message.CreateMessage(request.Version, null, bodyReader);
                changedMessage.Headers.CopyHeadersFrom(request.Headers);
                changedMessage.Properties.CopyProperties(request.Properties);
                request = changedMessage;
            }

            return null;
        }
Example #29
0
 public static void Main()
 {
     XslCompiledTransform xslt = new XslCompiledTransform();
     xslt.Load(XsltPath);
     xslt.Transform(CataloguePath, HtmlPath);
     Console.WriteLine("Successfully transformed in catalogue.html");
 }
Example #30
0
        public bool GenerateReport(string fileName)
        {
            bool retCode = false;
            ResetReportViwer();

            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load(rptXslPath);

            if ( File.Exists(fileName) == true)
            {
                XPathDocument myXPathDoc = new XPathDocument(fileName);
                StringWriter sw = new StringWriter();
                XmlWriter xmlWriter = new XmlTextWriter(sw);

                // using makes sure that we flush the writer at the end
                xslt.Transform(myXPathDoc, null, xmlWriter);
                xmlWriter.Flush();
                xmlWriter.Close();

                string xml = sw.ToString();

                HtmlDocument htmlDoc = axBrowser.Document;
                htmlDoc.Write(xml);
                retCode = true;
            }
            else
            {

                retCode = false;
            }

            return retCode;
        }
        private string ToHtml()
        {
            if (Services.StrandsCache.Contains(this))
            {
                return Services.StrandsCache.Read(this);
            }
            else
            {
                var transform = new XslCompiledTransform(true);
                var arguments = new XsltArgumentList();
                var settings = new XsltSettings();
                var readersettings = new XmlReaderSettings();
                //string xslsrc = (!string.IsNullOrEmpty(this.DisplayType)) ? "/XMLList.xsl" : "/Strands.xsl";
                //var xslfile = (this.Name == "themes") ? HttpContext.Current.Server.MapPath(this._xslAppUrl + "/StrandList.xsl") : HttpContext.Current.Server.MapPath(this._xslAppUrl + xslsrc);
                var xslfile = HttpContext.Current.Server.MapPath(this._xslAppUrl + ((!string.IsNullOrEmpty(this.DisplayType)) ? "XMLList.xsl" : this.XslName));

                settings.EnableDocumentFunction = true;
                settings.EnableScript = true;
                readersettings.DtdProcessing = DtdProcessing.Parse;
                readersettings.ValidationType = ValidationType.None;
                transform.Load(xslfile, settings, new XmlUrlResolver());
                arguments = TransformArguments(this);
                using (XmlReader reader = XmlReader.Create(this.GetDirectoryPath(), readersettings))
                {
                    System.IO.StringWriter writer = new System.IO.StringWriter();

                    transform.Transform(reader, arguments, writer);
                    return Services.StrandsCache.Write(this, writer.ToString());
                }
            }
        }
Example #32
0
        public static string XslTransInMemory(string xmlData, string xslData, XsltArgumentList argslist)
        {
            try
            {
                var xmlDoc = new XmlDocument();

                xmlDoc.LoadXml(xmlData);

                byte[] bytes     = System.Text.Encoding.UTF8.GetBytes(xslData);
                var    xslStream = new System.IO.MemoryStream(bytes)
                {
                    Position = 0
                };

                XmlReader xslStylesheet = default(System.Xml.XmlReader);
                xslStylesheet = new System.Xml.XmlTextReader(xslStream);

                var xslt = new System.Xml.Xsl.XslCompiledTransform();

                var settings = new System.Xml.Xsl.XsltSettings {
                    EnableDocumentFunction = true
                };

                xslt.Load(xslStylesheet, settings, null);

                var myWriter = new System.IO.StringWriter();
                xslt.Transform(xmlDoc, argslist, myWriter);

                return(myWriter.ToString());
            }
            catch (Exception ex)
            {
                return(ex.ToString() + " .............. " + xslData);
            }
        }
Example #33
0
 public static void Main()
 {
     XslCompiledTransform xslt = new XslCompiledTransform();
     xslt.Load("../../../14.catalog.xslt");
     xslt.Transform("..\\..\\..\\XmlCatalogDirectory\\text.xml", "../../../14. Catalog.html");
     Console.WriteLine("Successfully transformed!");
 }
Example #34
0
        public void Transform(string inputFilePath, string outputFilePath, KeyValueConfigurationCollection settings)
        {
            var xsltTemplateReader = new XmlTextReader(inputFilePath);
            var emptyDocumentReader = XmlReader.Create(new System.IO.StringReader("<empty />"));

            var writerSettings = new XmlWriterSettings();
            //settings.ConformanceLevel = ConformanceLevel.Fragment;
            writerSettings.Indent = true;

            using (var outputWriter = XmlWriter.Create(outputFilePath, writerSettings))
            {
                var xsltSettings = new XsltSettings();

                XsltArgumentList argumentList = new XsltArgumentList();

                var extensions = new XsltExtensionMethods(settings);

                argumentList.AddExtensionObject("http://core.com/config", extensions);
                argumentList.AddExtensionObject("http://setty.net/config", extensions);

                var transformer = new XslCompiledTransform(true);
                transformer.Load(xsltTemplateReader, xsltSettings, null);
                transformer.Transform(emptyDocumentReader, argumentList, outputWriter);
            }
        }
 private static void Main()
 {
     var xsl = new XslCompiledTransform();
     xsl.Load(Constants.FilePathForXslt);
     xsl.Transform(Constants.FilePathForCatalogue, SaveFilePath);
     Console.WriteLine("Catalogue.xml created in project folder.");
 }
 public static void Main()
 {
     XslCompiledTransform xslt = new XslCompiledTransform();
     xslt.Load("../../Catalog.xslt");
     xslt.Transform("../../Catalog.xml", "../../Catalog.html");
     Console.WriteLine("File Catalog.html is created.");
 }
 static void Main()
 {
     XslCompiledTransform xslt = new XslCompiledTransform();
     xslt.Load("../../style.xslt");
     xslt.Transform("../../../CatalogHolder/catalogue.xml", "../../catalogue.html");
     Console.WriteLine("result saved as catalogue.html");
 }
Example #38
0
    private void ApplyTransform()
    {
        var xslt = new System.Xml.Xsl.XslCompiledTransform();

        xslt.Load(FormData.XslTransformPath);
        xslt.Transform(FormData.InputSchemePath, FormData.OutputSchemePath);
        MessageBox.Show("Transform done", "Action completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
        //•	page-start-number: Page start number (default: 1)
        //•	page-setup-paper-width: Paper width in TWIPS (default: 11907 TWIPS = 21 cm, i.e. A4 format)
        //•	page-setup-paper-height: Paper height in TWIPS (default: 16840 TWIPS = 29.7 cm, i.e. A4 format)
        //•	page-setup-margin-top: Top margin in TWIPS (default: 1440 TWIPS = 1 inch = 2.54 cm)
        //•	page-setup-margin-bottom: Bottom margin in TWIPS (default: 1440 TWIPS = 1 inch = 2.54 cm)
        //•	page-setup-margin-left: Left margin in TWIPS (default: 1134 TWIPS = 2 cm)
        //•	page-setup-margin-right: Right margin in TWIPS (default: 1134 TWIPS = 2 cm)
        //•	font-size-default: Default font size in TWIPS (default: 20 TWIPS = 10 pt.)
        //•	font-name-default: Default font name (default: 'Times New Roman')
        //•	font-name-fixed: Default font name for fixed-width text, like PRE or CODE (default: 'Courier New')
        //•	font-name-barcode: Barcode font name (default: '3 of 9 Barcode')
        //•	header-font-size-default: Header default font size in TWIPS (default: 14 TWIPS = 7 pt.)
        //•	header-distance-from-edge: Default distance between top of page and top of header, in TWIPS (default: 720 TWIPS = 1.27 cm)
        //•	header-indentation-left: Header left indentation in TWIPS (default: 0)
        //•	footer-font-size-default: Footer default font size in TWIPS (default: 14 TWIPS = 7 pt.)
        //•	footer-distance-from-edge: Default distance between bottom of page and bottom of footer, in TWIPS (default: 720 TWIPS = 1.27 cm)
        //•	use-default-footer: Boolean flag: 1 to use default footer (page number and date) or 0 no footer (default: 1)
        //•	document-protected: Boolean flag: 1 protected (cannot be modified) or 0 unprotected (default: 1)
        //•	normalize-space: Boolean flag: 1 spaces are normalized and trimmed, or 0 no normalization no trim (default: 0)
        //•	my-normalize-space: Boolean flag: 1 spaces are normalized (NOT TRIMMED), or 0 no normalization (default: 1)


        public static string Html2Rtf(string html, NameValueCollection parameters)
        {
            // Load data.
            var xml = new System.Xml.XmlDocument();

            xml.Load(EngineHelper.GetResourceStream("Help.htm"));
            xml.DocumentElement.SetAttribute("xmlns", "http://www.w3.org/1999/xhtml");
            xml.DocumentElement.SetAttribute("xmlns:xhtml2rtf", "http://www.lutecia.info/download/xmlns/xhtml2rtf");
            //xml.DocumentElement.SetAttribute("SelectionLanguage", "XPath");
            //xml.DocumentElement.SetAttribute("SelectionNamespaces", "xmlns='http://www.w3.org/1999/xhtml' xmlns:xhtml='http://www.w3.org/1999/xhtml'");
            xml.Load(new StringReader(xml.OuterXml));
            // Load style sheet.
            var xslDoc = new System.Xml.XmlDocument();

            xslDoc.Load(EngineHelper.GetResourceStream("xhtml2rtf.xsl"));
            //xslDoc.DocumentElement.SetAttribute("SelectionLanguage", "XPath");
            //xslDoc.DocumentElement.SetAttribute("SelectionNamespaces", "xmlns:xhtml='http://www.w3.org/1999/xhtml' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
            //xslDoc.Load(new StringReader(xslDoc.OuterXml));
            // Create namespace manager.
            XmlNamespaceManager man = new XmlNamespaceManager(xslDoc.NameTable);

            man.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");

            // Set parameters in stylesheet
            if (parameters != null)
            {
                foreach (var name in parameters.AllKeys)
                {
                    var value    = parameters[name];
                    var xmlParam = xslDoc.DocumentElement.SelectSingleNode("//xsl:param[@name='" + name + "']", man);
                    if (xmlParam != null)
                    {
                        var xmlParamValue = xmlParam.SelectSingleNode("@select", man);
                        if (xmlParamValue != null)
                        {
                            xmlParamValue.InnerText = value;
                        }
                    }
                }
            }
            // Load the String into a TextReader
            System.IO.StringReader tr = new System.IO.StringReader(xslDoc.OuterXml);
            // Use that TextReader as the Source for the XmlTextReader
            System.Xml.XmlReader xr = new System.Xml.XmlTextReader(tr);
            // Create a new XslTransform class
            var xsl = new System.Xml.Xsl.XslCompiledTransform(true);

            // Load the XmlReader StyleSheet into the XslTransform class
            xsl.Load(xr, new XsltSettings(false, true), (XmlResolver)null);
            // Create output
            var sb = new System.Text.StringBuilder();
            var tw = new System.IO.StringWriter(sb);

            xsl.Transform(xml, (XsltArgumentList)null, tw);
            // Return RTF document.
            return(sb.ToString());
        }
Example #40
0
        public static void ValidateXslt(this string str)
        {
            var com = new System.Xml.Xsl.XslCompiledTransform();

            using (var reader = XmlReader.Create(new StringReader(str)))
            {
                com.Load(reader);
            }
        }
Example #41
0
        //
        // .ctor
        //


        public System.Xml.XPath.XPathNavigator TransformData(System.Xml.XPath.XPathNavigator nav, int cacheduration, IPDFDataSource source, PDFDataContext context)
        {
            //Check we have something to use for a transformation.
            if (string.IsNullOrEmpty(this.XSLTPath) && null == this.Transformer)
            {
                return(nav);
            }

            System.Xml.XmlWriter   xmlWriter    = null;
            System.IO.MemoryStream memoryStream = null;
            System.IO.StreamWriter streamWriter = null;
            System.Xml.XmlDocument result       = null;

            System.Xml.XmlDocument output = new System.Xml.XmlDocument();
            try
            {
                System.Xml.Xsl.XslCompiledTransform trans = this.DoGetTransformer(cacheduration, source, context);
                System.Xml.Xsl.XsltArgumentList     args  = this.DoGetArguments(context);
                memoryStream = new System.IO.MemoryStream();
                streamWriter = new System.IO.StreamWriter(memoryStream, Encoding.UTF8);

                System.Xml.XmlWriterSettings writerSettings = CreateWriterSettings();
                xmlWriter = System.Xml.XmlWriter.Create(streamWriter, writerSettings);

                trans.Transform(nav, args, xmlWriter);
                xmlWriter.Flush();
                streamWriter.Flush();

                result = new System.Xml.XmlDocument();
                memoryStream.Position = 0;
                result.Load(memoryStream);
            }
            catch (Exception ex)
            {
                throw new PDFDataException(Errors.CouldNotTransformInputData, ex);
            }
            finally
            {
                if (null != xmlWriter)
                {
                    xmlWriter.Close();
                }
                if (null != streamWriter)
                {
                    streamWriter.Dispose();
                }
                if (null != memoryStream)
                {
                    memoryStream.Dispose();
                }
            }

            return(result.CreateNavigator());
        }
Example #42
0
        /*        public static System.Xml.XmlDocument XslTransform(System.Xml.XPath.IXPathNavigable xmlSourceDoc, System.Xml.Xsl.XslCompiledTransform xsltDoc)
         *      {
         *          System.IO.MemoryStream outputStream = new System.IO.MemoryStream();
         *          System.Xml.XmlDocument outputDoc = new System.Xml.XmlDocument();
         *
         *          xsltDoc.Transform(xmlSourceDoc, null, outputStream);
         *          if (outputStream.Length != 0)
         *              outputStream.Position = 0;
         *
         *          // if it's a node, it's a partial doc
         *          if (xmlSourceDoc is System.Xml.XmlDocument)
         *              outputDoc.Load(outputStream);
         *          else
         *          {
         *              byte[] buff = new byte[outputStream.Length];
         *              outputStream.Read(buff, 0, buff.Length);
         *              System.Text.StringBuilder sb = new StringBuilder(buff.Length);
         *              System.Web.HttpContext.Current.Response.OutputStream.Write(buff, 0, buff.Length);
         *              System.Web.HttpContext.Current.Response.End();
         *              return null;
         *              sb.Append(Encoding.ASCII.GetChars(buff));
         *              sb.Replace("?", string.Empty);
         *              outputDoc.LoadXml("<html>" + sb.ToString() + "</html>");
         *          }
         *          return outputDoc;
         *      }
         */

        public static System.Xml.Xsl.XslCompiledTransform GetXslCompiledTransform(string xsltFilename)
        {
            System.Xml.Xsl.XslCompiledTransform xslTransform = (System.Xml.Xsl.XslCompiledTransform)RestNet.Cache.Get(xsltFilename);
            if (xslTransform == null)
            {
                xslTransform = new System.Xml.Xsl.XslCompiledTransform();
                xslTransform.Load(new XmlTextReader(xsltFilename), XsltSettings.TrustedXslt, new XmlUrlResolver());
                string[] fnTemp = { xsltFilename };
                RestNet.Cache.Set(xsltFilename, xslTransform, fnTemp, null, true, TimeSpan.MaxValue);
            }
            return(xslTransform);
        }
Example #43
0
        public static System.Xml.Xsl.XslCompiledTransform GetXSLContent(string ContentURL)
        {
            System.Xml.Xsl.XslCompiledTransform functionReturnValue = null;

            functionReturnValue = new System.Xml.Xsl.XslCompiledTransform();
            WebRequest  req             = WebRequest.Create(ContentURL);
            WebResponse result          = req.GetResponse();
            Stream      ReceiveStream   = result.GetResponseStream();
            XmlReader   objXSLTransform = new XmlTextReader(result.GetResponseStream());

            functionReturnValue.Load(objXSLTransform, null, null);
            return(functionReturnValue);
        }
Example #44
0
        protected virtual System.Xml.Xsl.XslCompiledTransform DoGetTransformer(int cacheduration, IPDFDataSource source, PDFDataContext context)
        {
            if (null == _transformer)
            {
                string path = this.XSLTPath;
                if (string.IsNullOrEmpty(path))
                {
                    throw new NullReferenceException(string.Format(Errors.XSLTPathOrTransformerNotSetOnInstance, source.ID));
                }

                path = source.MapPath(path);
                IPDFCacheProvider cache = ((Scryber.Components.Document)source.Document).CacheProvider;
                System.Xml.Xsl.XslCompiledTransform transformer;

                object found;

                if (cacheduration > 0 && cache.TryRetrieveFromCache(XSLTCacheType, path, out found))
                {
                    transformer = (System.Xml.Xsl.XslCompiledTransform)found;
                }
                else
                {
                    transformer = new System.Xml.Xsl.XslCompiledTransform(XSLTUseDebug);
                    try
                    {
                        transformer.Load(path);
                    }
                    catch (Exception ex)
                    {
                        throw new PDFDataException(string.Format(Errors.XSLTCouldNotBeLoadedFromPath, path), ex);
                    }

                    if (cacheduration > 0)
                    {
                        cache.AddToCache(XSLTCacheType, path, transformer, new TimeSpan(0, cacheduration, 0));
                    }
                }

                _transformer = transformer;
            }

            return(_transformer);
        }
Example #45
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="xslt"></param>
        /// <param name="pathDoc"></param>
        /// <param name="uriPrms"></param>
        /// <returns></returns>
        public static string TransformXSLToHTML(string xslFilePath, XPathDocument pathDoc)
        {
            System.Xml.Xsl.XslCompiledTransform xslTransform = new System.Xml.Xsl.XslCompiledTransform();
            XsltArgumentList arg = GetArgumentListFromUrl();

            //SET SETTINGS
            XmlReaderSettings set = new XmlReaderSettings();

            set.ProhibitDtd = false;
            set.XmlResolver = null;
            XmlReader xslRdr = XmlReader.Create(xslFilePath);

            xslTransform.Load(xslRdr);

            //TRANSFORM
            System.IO.StringWriter sw = new System.IO.StringWriter();
            xslTransform.Transform(pathDoc, arg, sw);
            return(System.Web.HttpUtility.HtmlDecode(sw.ToString()));
        }
Example #46
0
        public static string Transform(string xslFilePath, XsltArgumentList arg, string xmlUrl, string controlId, string cacheDuration)
        {
            System.Xml.Xsl.XslCompiledTransform xslTransform = new System.Xml.Xsl.XslCompiledTransform();
            xslTransform.Load(xslFilePath);

            //Add helper class
            XslFunctions func = new XslFunctions(HttpContext.Current.Request.Url.ToString());

            if (arg == null)
            {
                arg = new XsltArgumentList();
            }
            arg.AddExtensionObject("awp:functions", func);

            //TRANSFORM
            System.IO.StringWriter sw = new System.IO.StringWriter();
            xslTransform.Transform(xmlUrl, arg, sw);
            return(System.Web.HttpUtility.HtmlDecode(sw.ToString()));
        }
        /// <summary>
        /// 获得Docx文件用xslt转出来的html字符串
        /// </summary>
        /// <param name="titleStyleId">论文标题样式Id</param>
        /// <returns>xslt转出来的html字符串</returns>
        public string TransToStr(string titleStyleId, string authorInfo, string affiliationInfo)
        {
            //用来接收将xml转成html的流
            MemoryStream ms = new MemoryStream();

            //xslt编译转换对象
            System.Xml.Xsl.XslCompiledTransform trans = new System.Xml.Xsl.XslCompiledTransform();//------------trans
            //xslt参数对象
            XsltArgumentList argsList = new XsltArgumentList();

            argsList.AddParam("titleStyleId", "", titleStyleId);
            //将作者信息html作为参数 传入到xslt文件中
            argsList.AddParam("authorInfo", "", authorInfo);
            //将单位信息html作为参数 传入到xslt文件中
            argsList.AddParam("affiliationInfo", "", affiliationInfo);

            //根据xslt文件路径读取 xslt文件内容
            using (StreamReader rdr = new StreamReader(new FileStream(this.xsltpath, FileMode.Open)))
            {
                //将读到的xslt内容加载到XmlReader里面
                using (XmlReader xmlRdr = new XmlTextReader(rdr))
                {
                    //将xmlRdr内容加载到trans里面
                    trans.Load(xmlRdr);
                }
            }
            //创建一个新的XmlDocument对象
            XmlDocument document = new XmlDocument();//------------document

            //用document对象加载xml内容
            document.LoadXml(this.xmlcontent);

            trans.Transform(document, argsList, ms);

            ms.Position = 0;
            StreamReader reader = new StreamReader(ms, Encoding.UTF8);
            string       result = reader.ReadToEnd();

            return(result);
        }
Example #48
0
        public string GetOriginalChain(string stringXML)
        {
            StringWriter sw = new StringWriter();

            try
            {
                XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform();
                XsltSettings         sets = new XsltSettings(true, true);
                var resolver = new XmlUrlResolver();
                xslt.Load(xsltPath, sets, resolver);

                XmlDocument FromXmlFile = new System.Xml.XmlDocument();
                FromXmlFile.LoadXml(stringXML);

                xslt.Transform(FromXmlFile, null, sw);
            }
            catch (Exception ex)
            {
                throw new Exception("No se pudo generar la cadena", ex.InnerException);
            }
            return(sw.ToString());
        }
Example #49
0
        public static string XslTrans(string xmlData, string xslFilePath)
        {
            try
            {
                var xmlDoc = new XmlDocument();

                xmlDoc.LoadXml(xmlData);

                var xslt = new System.Xml.Xsl.XslCompiledTransform();

                xslt.Load(xslFilePath);

                var myWriter = new System.IO.StringWriter();
                xslt.Transform(xmlDoc, null, myWriter);

                return(myWriter.ToString());
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
Example #50
0
        public string GetXmlPage(string templatePath, string dataPath)
        {
            if (templatePath == null)
            {
                throw new ArgumentNullException("Missing xslt template path. Set XsltTemplatePath for ILayoutService in controller's constructor");
            }

            string xsl = templatePath;
            string xml = dataPath;

            System.Xml.XPath.XPathDocument doc   = new System.Xml.XPath.XPathDocument(xml);
            XslCompiledTransform           trans = new System.Xml.Xsl.XslCompiledTransform();

            trans.Load(xsl);

            StringWriter writer = new StringWriter();

            trans.Transform(doc, null, writer);

            var decoded = HttpUtility.HtmlDecode(writer.ToString());

            return(decoded.ToString());
        }
Example #51
0
        /// <summary>
        ///   Loads the stylesheet into the transform engine
        /// </summary>
        private System.Xml.Xsl.XslCompiledTransform GetXslTransform(string xslsrc, int portalId)
        {
            if (!string.IsNullOrEmpty(xslsrc))
            {
                switch (Globals.GetURLType(xslsrc))
                {
                case TabType.Url:
                    return(GetXslContentByWebRequest(xslsrc, ProhibitDtd, EnableDocument, EnableScript));

                default:

                    var trans = new System.Xml.Xsl.XslCompiledTransform();
                    using (var compiledStylesheet = Utils.CreateXmlReader(xslsrc, portalId, ProhibitDtd))
                    {
                        var settings = new XsltSettings(EnableDocument, EnableScript);
                        trans.Load(compiledStylesheet, settings, new XmlUrlResolver());
                    }

                    return(trans);
                }
            }
            return(null);
        }
Example #52
0
        /// <summary>
        ///   GetXSLContent loads the xsl content into an Xsl.XslCompiledTransform
        /// </summary>
        /// <param name = "contentUrl">The url to the xsl text</param>
        /// <param name = "prohibitDtd"></param>
        /// <returns>A XslCompiledTransform</returns>
        private static System.Xml.Xsl.XslCompiledTransform GetXslContentByWebRequest(string contentUrl, bool prohibitDtd, bool enableDocument, bool enableScript)
        {
            var xslCompiledTransform = new System.Xml.Xsl.XslCompiledTransform();
            var req = Globals.GetExternalRequest(contentUrl);

            using (var result = req.GetResponse())
            {
                using (var receiveStream = result.GetResponseStream())
                {
                    if (receiveStream != null)
                    {
                        var xmlReaderSettings = new XmlReaderSettings();
                        xmlReaderSettings.DtdProcessing = DtdProcessing.Prohibit;
                        using (var objXslTransform = XmlReader.Create(receiveStream, xmlReaderSettings))
                        {
                            var settings = new XsltSettings(enableDocument, enableScript);
                            xslCompiledTransform.Load(objXslTransform, settings, new XmlUrlResolver());
                        }
                    }
                }
            }
            return(xslCompiledTransform);
        }
Example #53
0
 /// <summary>
 /// Begins the style preparation.
 /// </summary>
 /// <remarks>Documented by Dev02, 2008-09-12</remarks>
 public static void BeginStylePreparation(string stylesheetPath)
 {
     stylePrepareThread = new Thread(delegate()
     {
         try
         {
             Debug.WriteLine("Style preparation thread started.");
             serializer            = new XmlSerializer(typeof(Style));
             versionTransform10_11 = new System.Xml.Xsl.XslCompiledTransform();
             XsltSettings settings = new XsltSettings(true, false); //enable document() function
             versionTransform10_11.Load(Path.Combine(stylesheetPath, @"System\Transformer\versionTransform10_11.xsl"), settings, null);
             Debug.WriteLine("Style preparation thread finished successfully.");
         }
         catch (Exception exp)
         {
             Trace.WriteLine("Style preparation thread crashed: " + exp.ToString());
         }
     });
     stylePrepareThread.IsBackground     = true;
     stylePrepareThread.Name             = "Style Preparation Thread";
     stylePrepareThread.CurrentCulture   = Thread.CurrentThread.CurrentCulture;
     stylePrepareThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
     stylePrepareThread.Start();
 }
Example #54
0
 public static System.Xml.Xsl.XslCompiledTransform GetXslCompiledTransform(XmlDocument xsltDocument)
 {
     System.Xml.Xsl.XslCompiledTransform xslTransform = new System.Xml.Xsl.XslCompiledTransform();
     xslTransform.Load(xsltDocument, XsltSettings.TrustedXslt, new XmlUrlResolver());
     return(xslTransform);
 }
Example #55
0
 public static string XslTransformToString(System.Xml.XPath.IXPathNavigable xmlSourceDoc, System.Xml.Xsl.XslCompiledTransform stylesheet)
 {
     System.IO.StringWriter sResult = new System.IO.StringWriter();
     stylesheet.Transform(xmlSourceDoc, null, sResult);
     return(sResult.ToString());
 }
Example #56
0
 public static string XslTransformToString(System.Xml.XPath.IXPathNavigable xmlSourceDoc, string xsltFilename)
 {
     System.Xml.Xsl.XslCompiledTransform stylesheet = GetXslCompiledTransform(GetFullXmlFilename(xsltFilename));
     return(XslTransformToString(xmlSourceDoc, stylesheet));
 }
Example #57
0
 public static System.Xml.XmlDocument XslTransform(System.Xml.XPath.IXPathNavigable xmlSourceDoc, string xsltFilename, XsltArgumentList xslArgs)
 {
     System.Xml.Xsl.XslCompiledTransform stylesheet = GetXslCompiledTransform(GetFullXmlFilename(xsltFilename));
     return(XslTransform(xmlSourceDoc, stylesheet, xslArgs));
 }
Example #58
0
 public static System.Xml.XmlDocument XslTransform(System.Xml.XPath.IXPathNavigable xmlSourceDoc, System.Xml.Xsl.XslCompiledTransform xsltDoc)
 {
     return(XslTransform(xmlSourceDoc, xsltDoc, null));
 }
Example #59
0
        public static System.Xml.XmlDocument XslTransform(System.Xml.XPath.IXPathNavigable xmlSourceDoc, System.Xml.Xsl.XslCompiledTransform xsltDoc, XsltArgumentList xslArgs)
        {
            System.Xml.XmlDocument outputDoc = new System.Xml.XmlDocument();
            System.IO.MemoryStream ms        = new System.IO.MemoryStream();

            xsltDoc.Transform(xmlSourceDoc, xslArgs, ms);
            ms.Position = 0;

            outputDoc.Load(ms);

            return(outputDoc);
        }
Example #60
0
    // Code for input validation
    static int Idoit(string csv, string xsltstr, string outputcsvfile, bool outputheader, string xsdstr, out string firstErrors)
    {
        XDocument doc = ConvertCsvToXML(csv, new[] { "," });

        Upx upx;

        upx.startrectype63  = 0;
        upx.startrectype64  = 0;
        upx.outputrectype60 = false;

        firstErrors = "";
        if (outputheader == true && xsdstr.Length > 0)
        {
            int          errorcount = 0;
            string       errstr     = "";
            XmlSchemaSet schemas    = new XmlSchemaSet();
            schemas.Add("", System.Xml.XmlReader.Create(new StringReader(xsdstr)));

            doc.Validate(schemas, (o, e) =>
            {
                // Console.WriteLine("{0}", e.Message);
                if (e.Message.IndexOf("attribute is not declared") == -1)
                {
                    if (errorcount < 20)
                    {
                        errstr += e.Message + "\n";
                    }
                    errorcount++;
                }
            });

            if (errorcount > 0)
            {
                firstErrors = errstr;
                Console.WriteLine(errstr);
                return(errorcount);
            }
        }

        XDocument newDoc = new XDocument();

        using (System.Xml.XmlWriter writer = newDoc.CreateWriter())
        {
            System.Xml.Xsl.XslCompiledTransform xslt     = new System.Xml.Xsl.XslCompiledTransform();
            System.Xml.Xsl.XsltSettings         settings = new System.Xml.Xsl.XsltSettings()
            {
                EnableDocumentFunction = true
            };
            xslt.Load(System.Xml.XmlReader.Create(new StringReader(xsltstr)), settings, new System.Xml.XmlUrlResolver());
            xslt.Transform(doc.CreateReader(), writer);
            //System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform();
            //xslt.Load(System.Xml.XmlReader.Create(new StringReader(xsltstr)));
            //xslt.Transform(doc.CreateReader(), writer);
        }

        string ext = Path.GetExtension(outputcsvfile);

        if (ext == ".csv")
        {
            converttocsv(newDoc, outputcsvfile, "rec", RowDelimit.NewLine, ColumnDelimit.Comma, outputheader);
        }
        if (ext == ".upx")
        {
            Console.WriteLine("=======GENERATING UPX=========");
            converttoupx(newDoc, outputcsvfile, "rec", RowDelimit.NewLine, ColumnDelimit.Comma, outputheader, ref upx);
        }

        return(0);
    }