Transform() 공개 메소드

public Transform ( IXPathNavigable input, XmlWriter results ) : void
input IXPathNavigable
results System.Xml.XmlWriter
리턴 void
예제 #1
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();
        }
        /// <summary>
        /// Displays the description of the project that is clicked.
        /// </summary>
        /// <param name="sender">Link on the project name</param>
        /// <param name="e">Arguments given to this command (project id)</param>
        public void description_Click(Object sender, EventArgs e)
        {
            ProjectAccess projectAccess = new ProjectAccess();

            // gets path to the xslt file
            string path = Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, @"xslt\fullProjectDescription.xslt");

            // Gets id of the project that must be displayed
            LinkButton description = sender as LinkButton;
            int idProject = Int32.Parse((string)description.CommandArgument);

            // Gets project data from database
            Project project = projectAccess.getProject(idProject);

            List<Technology> technos = projectAccess.getTechnologyProject(idProject);

            // Loads xslt file and executes the transformation to html. Result is stored in a StringWriter.
            string xml = "<project>\n";
            xml += "<title>" + project.Name + "</title>\n";
            xml += "<abreviation>" + project.Abreviation + "</abreviation>\n";
            xml += "<description>" + project.Description + "</description>\n";
            xml += "<nbStudent>" + project.NbStudents + "</nbStudent>\n";
            xml += "<technologies>\n";
            foreach(Technology techno in technos){
                xml += "<technology>" + techno.Name + "</technology>\n";
            }
            xml += "</technologies>\n";
            xml += "</project>\n";

            XPathDocument doc = new XPathDocument(new StringReader(xml));
            XslCompiledTransform xslt = new XslCompiledTransform();
            StringWriter sw = new StringWriter();

            xslt.Load(path);

            // get image from database
            byte[] image = projectAccess.getImage(idProject);

            if (image != null)
            {
                string encodedImage = "data:image/jpg;base64,";
                encodedImage += base64Encode(image);
                XsltArgumentList argsList = new XsltArgumentList();
                argsList.AddParam("IMAGE", "", encodedImage);
                xslt.Transform(doc, argsList, sw);
            }
            else
                xslt.Transform(doc, null, sw);

            descriptionPanel.Controls.Add(new LiteralControl(sw.ToString()));
        }
예제 #3
0
        public static bool runTransform(string xmlPath, string xsltPath, string outputPath, XsltArgumentList argList)
        {
            XmlTextReader reader = null;
            XmlWriter writer = null;
            try
            {
                XsltSettings xslt_set = new XsltSettings();
                xslt_set.EnableScript = true;
                xslt_set.EnableDocumentFunction = true;

                // Load the XML source file.
                reader = new XmlTextReader(xmlPath);

                // Create an XmlWriter.
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.Encoding = new UTF8Encoding();
                settings.OmitXmlDeclaration = false;

                writer = XmlWriter.Create(outputPath, settings);

                XslCompiledTransform xslt = new XslCompiledTransform();
                xslt.Load(xsltPath, xslt_set, new XmlUrlResolver());
                if (argList == null)
                    xslt.Transform(reader, writer);
                else
                    xslt.Transform(reader, argList, writer);
                reader.Close();
                writer.Close();

                return true;
            }
            catch (Exception err)
            {
                try
                {
                    if (reader != null)
                        reader.Close();
                    if (writer != null)
                        writer.Close();
                    throw (err);
                }
                catch (Exception err2)
                {
                    MessageBox.Show(err2.ToString());
                    return false;
                }
            }
        }
예제 #4
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();
        }
    }
예제 #5
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");
 }
        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());
        }
예제 #7
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);
        }
예제 #8
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());
        }
		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();
		}
예제 #10
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);
            }
        }
예제 #11
0
파일: XmlHelper.cs 프로젝트: HungNV88/CRM
 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);
 }
예제 #12
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;
        }
예제 #13
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;
        }
예제 #14
0
 public static void Main()
 {
     XslCompiledTransform xslt = new XslCompiledTransform();
     xslt.Load(XsltPath);
     xslt.Transform(CataloguePath, HtmlPath);
     Console.WriteLine("Successfully transformed in catalogue.html");
 }
예제 #15
0
        public static Stream BuildRDLCStream(
            DataSet data, string name, string reportResource)
        {
            using (MemoryStream schemaStream = new MemoryStream())
            {
                // save the schema to a stream
                data.WriteXmlSchema(schemaStream);
                schemaStream.Seek(0, SeekOrigin.Begin);

                // load it into a Document and set the Name variable
                XmlDocument xmlDomSchema = new XmlDocument();
                xmlDomSchema.Load(schemaStream);
                xmlDomSchema.DocumentElement.SetAttribute("Name", data.DataSetName);

                // Prepare XSL transformation
                using (var sr = new StringReader(reportResource))
                using (var xr = XmlReader.Create(sr))
                {
                    // load the report's XSL file (that's the magic)
                    XslCompiledTransform xform = new XslCompiledTransform();
                    xform.Load(xr);

                    // do the transform
                    MemoryStream rdlcStream = new MemoryStream();
                    XmlWriter writer = XmlWriter.Create(rdlcStream);
                    xform.Transform(xmlDomSchema, writer);
                    writer.Close();
                    rdlcStream.Seek(0, SeekOrigin.Begin);

                    // send back the RDLC
                    return rdlcStream;
                }
            }
        }
예제 #16
0
        public static void TransformHtml(XmlSerializer serializer, object report, Type reportType, string outputFilePath, GeneratorConfiguration generatorConfiguration, string xsltFile)
        {
            var xmlOutputWriter = new StringWriter();
            serializer.Serialize(xmlOutputWriter, report);

            XslCompiledTransform xslt = new XslCompiledTransform();
            var xsltSettings = new XsltSettings(true, false);
            XmlResolver resourceResolver;

            var reportName = reportType.Name.Replace("Generator", "");
            using (var xsltReader = GetTemplateReader(reportType, reportName, xsltFile))
            {
                resourceResolver = new XmlResourceResolver();
                xslt.Load(xsltReader, xsltSettings, resourceResolver);
            }

            var xmlOutputReader = new XmlTextReader(new StringReader(xmlOutputWriter.ToString()));

            XsltArgumentList argumentList = new XsltArgumentList();
            argumentList.AddParam("feature-language", "", generatorConfiguration.FeatureLanguage.Name);
            argumentList.AddParam("tool-language", "", generatorConfiguration.ToolLanguage.Name);
            
            using (var xmlTextWriter = new XmlTextWriter(outputFilePath, Encoding.UTF8))
            {
				xslt.Transform(xmlOutputReader, argumentList, xmlTextWriter, resourceResolver);
            }            
        }
예제 #17
0
partial         void UIButton6_TouchUpInside(UIButton sender)
        {
            var xslt = new XslCompiledTransform();

            using (var stringReader = new StringReader(txtXslt.Text))
            {
                using(var xmlReader = XmlReader.Create(stringReader))
                {
                    xslt.Load(xmlReader);
                }
            }

            using (var stringReader = new StringReader(txtXml.Text))
            {
                using (var xmlreader = XmlReader.Create(stringReader))
                {
                    try
                    {
                        var stringBuilder = new StringBuilder();
                        using (var xmlWriter = XmlWriter.Create(stringBuilder))
                        {
                            xslt.Transform(xmlreader, xmlWriter);
                        }
                        txtResult.Text = stringBuilder.ToString();
                    }
                    catch(Exception ex)
                    {
                        txtResult.Text = ex.Message;
                    }
                }
            }
        }
        /// <summary>
        /// Mutate a WiX document as a string.
        /// </summary>
        /// <param name="wix">The Wix document element as a string.</param>
        /// <returns>The mutated Wix document as a string.</returns>
        public override string Mutate(string wixString)
        {
            try
            {
                XslCompiledTransform xslt = new XslCompiledTransform();
                xslt.Load(this.transform, XsltSettings.TrustedXslt, new XmlUrlResolver());

                using (XmlTextReader xmlReader = new XmlTextReader(new StringReader(wixString)))
                {
                    using (StringWriter stringWriter = new StringWriter())
                    {
                        XmlWriterSettings xmlSettings = new XmlWriterSettings();
                        xmlSettings.Indent = true;
                        xmlSettings.IndentChars = "    ";
                        xmlSettings.OmitXmlDeclaration = true;

                        using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xmlSettings))
                        {
                            xslt.Transform(xmlReader, xmlWriter);
                        }

                        wixString = stringWriter.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                this.Core.OnMessage(UtilErrors.ErrorTransformingHarvestedWiX(this.transform, ex.Message));
                return null;
            }

            return wixString;
        }
예제 #19
0
        public void TransformOneXML(FileInfo xmlFile, FileInfo targetFile)
        {
            Steps.Log.Debug("Brug ProcessStartInfo class");
            Steps.Log.Debug("Skriv 'Transform -s:source -xsl:stylesheet -o:output'");

            Steps.Log.DebugFormat("Dvs: 'Transform -s:{0} -xsl:{1} -o:{2}'", xmlFile.FullName, XSLTFile.FullName,
                                          targetFile);

            try
            {
                XPathDocument myXPathDocument = new XPathDocument(xmlFile.FullName);
                var myXslTransform = new System.Xml.Xsl.XslCompiledTransform();
                XmlTextWriter writer = new XmlTextWriter(targetFile.FullName, Encoding.UTF8);
                myXslTransform.Load(XSLTFile.FullName);
                myXslTransform.Transform(myXPathDocument, null, writer);
                writer.Close();

                string id = xmlFile.Name.Replace("dataextract", "").Replace(".xml", "");
                string o = @"""";
                string[] lines = File.ReadAllLines(targetFile.FullName, Encoding.UTF8);
                for (int i = 0; i < lines.Length; i++)
                {
                    lines[i] = lines[i].Replace(" xmlns=" + o + o, "").Replace("Creator", "Creator " + id).Replace("1</eadid>", id+"</eadid>");
                }
                File.WriteAllLines(targetFile.FullName, lines, Encoding.UTF8);
            }
            catch (Exception e)
            {
                Steps.Log.Debug(e);
            }
        }
예제 #20
0
 public static void Main()
 {
     XslCompiledTransform xsltStyle = new XslCompiledTransform();
     xsltStyle.Load("../../catalogstyle.xslt");
     xsltStyle.Transform("../../catalog.xml", "../../catalog.html");
     Console.WriteLine("catalog.html created");
 }
예제 #21
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);
                }
        }
    }
예제 #22
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");
 }
예제 #23
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);
            }
        }
예제 #24
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();
            }
        }
예제 #25
0
파일: Program.cs 프로젝트: hj1980/Mosa
        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;
            }
        }
예제 #26
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();
				}
			}
		}
예제 #27
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!");
 }
예제 #28
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();
 }
 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.");
 }
예제 #30
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");
        }
예제 #31
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() ) );
        }
예제 #32
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();
        }
예제 #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);
            }
        }
예제 #34
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.");
 }
예제 #35
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;
		}
예제 #36
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);
            }
        }
        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();
        }
예제 #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);
    }
예제 #39
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());
        }
예제 #40
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());
        }
예제 #41
0
        /// <summary>
        /// Adds the styles from the given files.
        /// </summary>
        /// <param name="stylesheetPath">The stylesheet path, where the stylesheets of the styles could be found.</param>
        /// <param name="files">The files.</param>
        /// <remarks>Documented by Dev05, 2007-08-20</remarks>
        private void AddStyles(string stylesheetPath, string[] files)
        {
            string backupWorkingDir = Directory.GetCurrentDirectory();

            foreach (string file in files)
            {
                try
                {
                    AwaitStylePreparation(stylesheetPath, true);
                    FileInfo info = new FileInfo(file);
                    string   path = Path.GetDirectoryName(file) + @"\" + info.Name.Substring(0, info.Name.Length - info.Extension.Length);
                    Directory.SetCurrentDirectory(path);
                    using (Stream input = File.OpenRead(file))
                    {
                        Style style = (Style)serializer.Deserialize(input);

                        if (style.StyleVersion == "1.0")
                        {
                            //transform stylesheet version
                            input.Position = 0;
                            MemoryStream transformed = new MemoryStream();

                            XmlReader reader = XmlReader.Create(input);
                            XmlWriter writer = XmlWriter.Create(transformed);

                            versionTransform10_11.Transform(reader, writer);
                            transformed.Position = 0;
                            style = (Style)serializer.Deserialize(transformed);
                            style.StyleVersion = "1.1";
                        }

                        CheckStyles(stylesheetPath, style, ResourceManager);

                        style.AnswerStylesheetPath   = Path.Combine(stylesheetPath, style.AnswerStylesheetPath);
                        style.QuestionStylesheetPath = Path.Combine(stylesheetPath, style.QuestionStylesheetPath);
                        style.StylePath = Path.Combine(stylesheetPath, style.StylePath);

                        if (!Styles.ContainsKey(style.StyleName))
                        {
                            Styles.Add(style.StyleName, style);
                        }
                    }
                }
                catch (InvalidOperationException exp)
                {
                    System.Diagnostics.Trace.WriteLine("StyleHandler - InvalidOperationException: " + exp.ToString());
                }
                finally
                {
                    Directory.SetCurrentDirectory(backupWorkingDir);
                }
            }
        }
예제 #42
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);
        }
예제 #43
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()));
        }
예제 #44
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()));
        }
예제 #45
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);
        }
예제 #46
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());
        }
예제 #47
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());
            }
        }
예제 #48
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());
        }
예제 #49
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();
            }
        }
예제 #50
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);
    }
예제 #51
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());
 }
예제 #52
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);
            }
        }
예제 #53
0
        public void WriteZed(XmlReader input)
        {
            System.IO.StringWriter dataHolder = new System.IO.StringWriter();
            XmlWriter results = XmlWriter.Create((System.IO.TextWriter)dataHolder);

            string strDcDate = (string)TransformationArguments.GetParam("dcDate", "");

            if (strDcDate == null)
            {
                strDcDate = DateTime.Now.ToString("yyyy-MM-dd");
                TransformationArguments.AddParam("dcDate", "", strDcDate);
            }

            try
            {
                theTransformer.Transform(input, TransformationArguments, results);
            }
            catch (Exception eAnything)
            {
                results = null;
            }
            input.Close(); //Since the stream has been read to the end, we might as well close it.

            #region this region only needed for debugging, will be removed
            //TODO: the actual removal!
            string[] strSmilFiles = System.IO.Directory.GetFiles(strOutputDir, "*.smil");
            foreach (string aSmilFile in strSmilFiles)
            {
                System.IO.File.Delete(aSmilFile);
            }
            #endregion

            XmlDocument resDoc = new XmlDocument();
            resDoc.LoadXml(dataHolder.ToString());

            XmlWriterSettings fileSettings = new XmlWriterSettings();
            fileSettings.Indent = true;

            //TODO:Remove following line
            resDoc.Save(strOutputDir + "/raw.xml");


            XmlNamespaceManager xPathNSManager = new XmlNamespaceManager((XmlNameTable) new NameTable());
            xPathNSManager.AddNamespace("smil", "http://www.w3.org/2001/SMIL20/Language");
            xPathNSManager.AddNamespace("opf", "http://openebook.org/namespaces/oeb-package/1.0/");
            xPathNSManager.AddNamespace("ncx", "http://www.daisy.org/z3986/2005/ncx/");


            XmlNode ncxTree     = resDoc.DocumentElement.SelectSingleNode("//ncx:ncx", xPathNSManager);
            string  ncxFilename = (string)TransformationArguments.GetParam("ncxFilename", "");
            if (ncxFilename == "")
            {
                ncxFilename = "navigation.ncx";
            }
            XmlWriter ncxFile = XmlWriter.Create(strOutputDir + "/" + ncxFilename, fileSettings);
            ncxFile.WriteNode(ncxTree.CreateNavigator(), false);
            ncxFile.Close();
            ncxTree.ParentNode.RemoveChild(ncxTree); //remove the written bit


            #region Calculating running time, setting on smil file nodes as required

            TimeSpan prevDuration = new TimeSpan();
            try
            {
                string      tmpXpathStatement = "//*[self::smil:smil or self::smil:audio]";
                XmlNodeList lstAudAndSmil     = resDoc.DocumentElement.SelectNodes(tmpXpathStatement, xPathNSManager);

                for (int i = 0; i < lstAudAndSmil.Count; i++)
                {
                    XmlElement curElement = (XmlElement)lstAudAndSmil[i];
                    switch (curElement.LocalName)
                    {
                    case "smil":
                        XmlElement ndElapsed = (XmlElement)curElement.SelectSingleNode(".//smil:meta[@name='dtb:totalElapsedTime']", xPathNSManager);
                        ndElapsed.SetAttribute("content", prevDuration.ToString().TrimEnd(".0".ToCharArray()));
                        break;

                    case "audio":
                        try
                        {
                            prevDuration = prevDuration.Subtract(TimeSpan.Parse(curElement.GetAttribute("clipBegin")));
                        }
                        catch { }
                        try
                        {
                            prevDuration = prevDuration.Add(TimeSpan.Parse((curElement.GetAttribute("clipEnd"))));
                        }
                        catch { }
                        break;

                    default:

                        break;
                    }
                }
            }
            catch (Exception eAnything)
            {
                //TODO: Error forwarding
                System.Diagnostics.Debug.WriteLine(eAnything.ToString());
            }

            //TODO:Remove following line
            //resDoc.Save(strOutputDir + "/raw.xml");
            #endregion

            XmlElement metaDtbTotalDuration = (XmlElement)resDoc.SelectSingleNode("//opf:meta[@name='dtb:totalTime']", xPathNSManager);
            metaDtbTotalDuration.SetAttribute("content", prevDuration.ToString().TrimEnd(".0".ToCharArray()));

            XmlNode opfTree     = resDoc.DocumentElement.SelectSingleNode("//opf:package", xPathNSManager);
            string  opfFilename = (string)TransformationArguments.GetParam("packageFilename", "");
            if (opfFilename == "")
            {
                opfFilename = "package.opf";
            }
            XmlWriter opfFile = XmlWriter.Create(strOutputDir + "/" + opfFilename, fileSettings);
            opfFile.WriteNode(opfTree.CreateNavigator(), false);
            opfFile.Close();
            opfTree.ParentNode.RemoveChild(opfTree); //remove the written bit

            XmlNodeList smilTrees = resDoc.DocumentElement.SelectNodes("//smil:smil", xPathNSManager);
            for (int i = smilTrees.Count - 1; i > -1; i--)
            {
                XmlElement newRoot  = (XmlElement)smilTrees[i];
                XmlWriter  smilFile = XmlWriter.Create(strOutputDir + "/" + newRoot.GetAttribute("filename") + ".smil", fileSettings);
                newRoot.RemoveAttribute("filename");
                smilFile.WriteNode(newRoot.CreateNavigator(), false);
                smilFile.Close();
                newRoot.ParentNode.RemoveChild(newRoot);
            }

            //TODO:Remove following line
            //resDoc.Save(strOutputDir + "/raw.xml");

            XmlNodeList filesToCopy = resDoc.DocumentElement.SelectNodes("filenames/file", xPathNSManager);
            foreach (XmlNode fileNode in filesToCopy)
            {
                string strSourceFileName = strContextFolder + "\\" + fileNode.InnerText;
                strSourceFileName = strSourceFileName.Replace("/", "\\");

                string strDestFileName = fileNode.InnerText.Substring((fileNode.InnerText.LastIndexOf("/") > 0) ? fileNode.InnerText.LastIndexOf("/") + 1 : 0);
                strDestFileName = OuputDir + "\\" + strDestFileName;
                strDestFileName = strDestFileName.Replace("/", "\\");
                try
                {
                    System.IO.File.Copy(strSourceFileName, strDestFileName, true);
                }
                catch (Exception eAnything)
                {
                    System.Diagnostics.Debug.WriteLine(eAnything.ToString());
                }
            }
        }