Load() public method

public Load ( IXPathNavigable stylesheet ) : void
stylesheet IXPathNavigable
return void
Exemplo n.º 1
0
		/// <summary>
		/// Converts source XML with given transform with applying DSL
		/// </summary>
		/// <param name="xml"> </param>
		/// <returns>XElement with data, converted by transform</returns>
		/// <exception cref="XmlDslLoaderException">
		/// <list type="bullet">
		/// <item><description>cannot find transform file</description></item>
		/// <item><description>any problem with underlined XmlDslDefinition</description></item>
		/// </list>
		/// </exception>
		public XElement Load(XElement xml) {
			if (null == xml.Element("transform")) return xml; //no dsl needed
			var trdef = new XmlDslDefinition().Extract(xml);
			var langfile = Resolver.Resolve(Rootdir+"/" + trdef.LangName + ".xslt", false);
			if (!File.Exists(langfile))
			{
				throw new XmlDslLoaderException("Не возможно найти файл XML языка" + langfile);
			}
			var xsl = new XslCompiledTransform();
			if(trdef.NeedPrepareXslt) {
				var xsltcontent = XElement.Load(langfile);
				xsltcontent = trdef.PrepareXslt(xsltcontent);
				var resolver = new XmlDslRootBasedXmlUrlResolver(langfile);
				xsl.Load(xsltcontent.CreateReader(),XsltSettings.TrustedXslt,resolver);
			}else {
				xsl.Load(langfile, XsltSettings.TrustedXslt, new XmlUrlResolver());
			}
			var args = trdef.CreateArguments();
			var sw = new StringWriter();
			using (var xw = XmlWriter.Create(sw)) {
				xsl.Transform(xml.CreateReader(),args,xw);
				xw.Flush();
			}
			return XElement.Parse(sw.ToString());
		}
Exemplo n.º 2
0
        public void BuildNavigator(string modelFilePath)
        {
            XmlResolver resolver = new XmlUrlResolver();
            resolver.Credentials = CredentialCache.DefaultCredentials;
            XmlTextReader tr = new XmlTextReader(modelFilePath);
            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(this.stylesheetFilesPath + Path.DirectorySeparatorChar + "ModelTree.xsl",null,resolver);
            XmlTextWriter tw = new XmlTextWriter(this.htmlFilesPath + Path.DirectorySeparatorChar + "ModelTree.htm", Encoding.UTF8);
            XsltArgumentList al = new XsltArgumentList();
            al.AddParam("modelBrowser","",this.localizer.GetValue("Globals","ModelBrowser"));
            al.AddParam("glossary","",this.localizer.GetValue("Globals","Glossary"));
            al.AddParam("stakeholders", "", this.localizer.GetValue("Globals", "Stakeholders"));
            transform.Transform(tr,al,tw,null);
            tw.Close();
            tr.Close();

            tr = new XmlTextReader(modelFilePath);
            transform.Load(this.stylesheetFilesPath + Path.DirectorySeparatorChar + "HomePage.xsl",null,resolver);
            tw = new XmlTextWriter(this.htmlFilesPath + Path.DirectorySeparatorChar + "main.htm",Encoding.UTF8);
            al = new XsltArgumentList();
            AssemblyName an = this.GetType().Assembly.GetName();
            al.AddParam("version","",an.Version.ToString(3));
            al.AddParam("model", "", this.localizer.GetValue("Globals", "Model"));
            al.AddParam("author", "", this.localizer.GetValue("Globals", "Author"));
            al.AddParam("company", "", this.localizer.GetValue("Globals", "Company"));
            al.AddParam("creationDate", "", this.localizer.GetValue("Globals", "CreationDate"));
            al.AddParam("exportPrintDate", "", this.localizer.GetValue("Globals", "ExportPrintDate"));
            al.AddParam("now", "", Convert.ToString(DateTime.Now, DateTimeFormatInfo.InvariantInfo));
            al.AddParam("release", "", this.localizer.GetValue("Globals", "Release"));
            transform.Transform(tr,al,tw,null);
            tw.Close();
            tr.Close();
        }
Exemplo n.º 3
0
        public static string Transform (string xml, string xslFile, IDictionary<string, string> xslParams)
        {
            XslCompiledTransform xslTrans = new XslCompiledTransform ();
            xslTrans.Load (xslFile);

            return Transform (xml, xslTrans, xslParams);
        }
Exemplo n.º 4
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");
 }
Exemplo n.º 5
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 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;
        }
        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());
        }
Exemplo n.º 8
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);
                }
        }
    }
Exemplo n.º 9
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;
        }
Exemplo n.º 10
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!");
 }
Exemplo n.º 11
0
 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.");
 }
Exemplo n.º 12
0
 public static void Main()
 {
     XslCompiledTransform xsltStyle = new XslCompiledTransform();
     xsltStyle.Load("../../catalogstyle.xslt");
     xsltStyle.Transform("../../catalog.xml", "../../catalog.html");
     Console.WriteLine("catalog.html created");
 }
Exemplo n.º 13
0
        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;
        }
Exemplo n.º 14
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);
            }
        }
Exemplo n.º 15
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);
 }
		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();
		}
Exemplo n.º 17
0
        // initialize variables
        private void TransformTestForm_Load( object sender, EventArgs e )
        {
            transformer = new XslCompiledTransform(); // create transformer

             // load and compile the style sheet
             transformer.Load( "sports.xsl" );
        }
Exemplo n.º 18
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;
		}
Exemplo n.º 19
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");
        }
        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();
        }
Exemplo n.º 21
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);
            }
        }
Exemplo n.º 22
0
        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();
        }
Exemplo n.º 23
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;
            }
        }
Exemplo n.º 24
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);
            }
        }
 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 XsltTransformer()
  {
      _xsltTransform = new XslCompiledTransform();
      _xsltTransform.Load(@"..\..\PersonToEmployee.xsl");
      _xsltEnrich = new XslCompiledTransform();
      _xsltEnrich.Load(@"..\..\PersonToPerson.xsl");
 }
Exemplo n.º 27
0
		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();
				}
			}
		}
Exemplo n.º 28
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();
            }
        }
Exemplo n.º 29
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() ) );
        }
Exemplo n.º 30
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);
        }
Exemplo n.º 31
0
        //--- Class Constructor ---
        static ExtensionBL() {

            // load XSLT for normalizing extensions
            XDoc doc = Plug.New("resource://mindtouch.deki/MindTouch.Deki.Resources.ExtensionConverter.xslt").With(DreamOutParam.TYPE, MimeType.XML.FullType).Get().ToDocument();
            _extensionConverterXslt = new XslCompiledTransform();
            _extensionConverterXslt.Load(new XmlNodeReader(doc.AsXmlNode), null, null);
        }
Exemplo n.º 32
0
 public static string transform(this string xml, string xslt, IDictionary parameters)
 {
     var trans = new XslCompiledTransform();
     trans.Load(xslt.asXPathNavigable(), XsltSettings.TrustedXslt, new FilePathXmlResolver(myapp.files));
     var args = XsltStandardExtension.PrepareArgs();
     if (null != parameters)
     {
         foreach (var parameter in parameters.Keys)
         {
             var nameorns = parameter.ToString();
             var paramorext = parameters[parameter];
             bool ext = true;
             if (paramorext is XPathNavigator || paramorext is XPathNavigator || paramorext is string || paramorext is ValueType)
             {
                 ext = false;
             }
             if (ext)
             {
                 args.AddExtensionObject(nameorns, paramorext);
             }
             else
             {
                 args.AddParam(nameorns, string.Empty, paramorext);
             }
         }
     }
     var sw = new StringWriter();
     trans.Transform(xml.asXPathNavigable(), args, sw);
     return sw.ToString();
 }
Exemplo n.º 33
0
        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);
            }
        }
Exemplo n.º 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);
            }
        }
Exemplo n.º 35
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());
        }
Exemplo n.º 36
0
 public static void Main()
 {
     XslCompiledTransform xslt = new XslCompiledTransform();
     xslt.Load(XsltPath);
     xslt.Transform(CataloguePath, HtmlPath);
     Console.WriteLine("Successfully transformed in catalogue.html");
 }
Exemplo n.º 37
0
 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");
 }
Exemplo n.º 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);
    }
Exemplo n.º 39
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);
            }
        }
Exemplo n.º 40
0
        //•	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());
        }
Exemplo n.º 41
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);
        }
Exemplo n.º 42
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);
        }
Exemplo n.º 43
0
 public XukToZed()//string pathToStylesheet)
 {
     try
     {
         Assembly    assembly         = Assembly.GetExecutingAssembly();
         string      pathToStylesheet = "XukToZed.xslt";
         XslResolver theResolver      = new XslResolver(this.GetType());
         theTransformer.Load(pathToStylesheet, null, theResolver);
     }
     catch (Exception loadException)
     {
         System.Diagnostics.Debug.WriteLine(loadException.ToString());
         throw (loadException);
     }
 }
Exemplo n.º 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);
        }
Exemplo n.º 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()));
        }
Exemplo n.º 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()));
        }
Exemplo n.º 47
0
        /// <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);
        }
Exemplo n.º 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());
        }
Exemplo n.º 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());
            }
        }
Exemplo n.º 50
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);
        }
Exemplo n.º 51
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());
        }
Exemplo n.º 52
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);
        }
Exemplo n.º 53
0
        void Transform()
        {
            try
            {
                if (inputChanged)
                {
                    Utils.WriteFile(inputFilePath, tbInput.Text);
                    inputChanged = false;
                }
                if (xslChanged)
                {
                    Utils.WriteFile(xslFilePath, tbXsl.Text);
                    xslChanged = false;
                }

                using (WaitCursor wc = new WaitCursor())
                {
                    xslt.Load(xslFilePath);
                    xslt.Transform(inputFilePath, outputFilePath);
                }

                using (StreamReader sr = new StreamReader(outputFilePath))
                {
                    tbOutput.Text = sr.ReadToEnd();
                }

                this.tcFiles.SelectedTab = tpOutput;
            }
            catch (Exception ex)
            {
                OnException(ex);
            }
            finally
            {
                UpdateControls();
            }
        }
Exemplo n.º 54
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();
 }
Exemplo n.º 55
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);
 }
Exemplo n.º 56
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);
    }
Exemplo n.º 57
0
        protected virtual void TranformXslt(string xml, string xsl, string outputFile)
        {
            //XmlTextWriter writer = null;
            string guid           = "." + Guid.NewGuid().ToString();
            string tempOutputFile = outputFile + guid;

            //try
            //{
            // XPathDocument myXPathDocument = new XPathDocument(xml);//loading the original xml

            System.Xml.Xsl.XslCompiledTransform myXslTransform = new System.Xml.Xsl.XslCompiledTransform();

            //writer = new XmlTextWriter(outputFile,null);//loading the output xml


            try
            {
                myXslTransform.Load(xsl);    //loading xslt file to transformer
            }
            catch (ArgumentNullException)
            {
                throw new DuradosException("The xml transformation failed while loading the xsl. Xsl file was not provided.");
            }
            catch (XsltException exception)
            {
                throw new DuradosException("The xml transformation failed while loading the xsl. " + exception.Message, exception);
            }
            catch (FileNotFoundException)
            {
                throw new DuradosException("The xml transformation failed while loading the xsl. The xsl file: " + xsl + " was not found");
            }
            catch (UriFormatException exception)
            {
                throw new DuradosException("The xml transformation failed while loading the xsl. The xsl file: " + xsl + " format has errors", exception);
            }
            catch (XmlException exception)
            {
                throw new DuradosException("The xml transformation failed while loading the xsl. The xsd file: " + xml + " format has errors", exception);
            }
            catch (Exception exception)
            {
                throw new DuradosException("The xml transformation failed while loading the xsl.", exception);
            }



            try
            {
                myXslTransform.Transform(xml, tempOutputFile);

                // myXslTransform.Transform(myXPathDocument, null, writer);
            }
            catch (XsltException exception)
            {
                throw new DuradosException("The xml transformation failed while transform to xml. " + exception.Message, exception);
            }
            catch (XmlException exception)
            {
                throw new DuradosException("The xml transformation failed while transform to xml.", exception);
            }


            try
            {
                if (xml == outputFile)
                {
                    System.IO.File.Delete(xml);
                }
                System.IO.File.Move(tempOutputFile, outputFile);
            }

            catch (ArgumentNullException)
            {
                throw new DuradosException("The xml transformation failed while writing the output xml. output file was not provided.");
            }

            catch (FileNotFoundException)
            {
                throw new DuradosException("The xml transformation failed while writing the output xml. The output file: " + outputFile + " was not found");
            }
            catch (DirectoryNotFoundException)
            {
                throw new DuradosException("The xml transformation failed while writing the output xml. The output directory of: " + outputFile + " was not found");
            }
            catch (UnauthorizedAccessException exception)
            {
                throw new DuradosException("The xml transformation failed while writing the output xml. :Unauthorized Access to " + outputFile + " or " + xml, exception);
            }
        }