public void Action() { string xml = "<?xml version=\"1.0\"?>\n<a><b c=\"d\">e</b></a>"; string xsl = "<?xml version=\"1.0\"?>\n" + "<xsl:stylesheet version=\"1.0\" " + "xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" " + "xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\" " + "xmlns:js=\"urn:js\" " + ">" + "<msxsl:script language=\"jsCrIpt\" implements-prefix=\"js\">" + "function SimpleTest() { return \"JScript test\"; }" + "</msxsl:script>" + "<xsl:template match=\"a\"><foo><xsl:apply-templates/></foo></xsl:template>" + "<xsl:template match=\"b\"><xsl:element name=\"bar\">" + "<xsl:attribute name=\"simpleTest\"><xsl:value-of select=\"js:SimpleTest()\"/></xsl:attribute>" + "</xsl:element></xsl:template>" + "<xsl:template match=\"/\"><xsl:apply-templates/></xsl:template>" + "</xsl:stylesheet>"; XPathDocument myXPathDocument = new XPathDocument(new XmlTextReader(new StringReader(xml))); XslTransform myXslTransform = new XslTransform(); myXslTransform.Load(new XmlTextReader(new StringReader(xsl))); StringWriter myStringWriter = new StringWriter(); XmlTextWriter myXmlWriter = new XmlTextWriter(myStringWriter); myXmlWriter.Formatting = Formatting.Indented; myXslTransform.Transform(myXPathDocument, null, myXmlWriter); myXmlWriter.Close(); Console.WriteLine(myStringWriter.ToString()); }
static void Main(string[] args) { try { if (args.Length < 2) { Console.WriteLine("usage: <gedcomFileName> <xmlOutputFileName> [-s <xsltFileName>]"); return; } string gedcomFileName = args[0]; string outputFileName = args[1]; string xsltFileName = ""; GedcomReader gr = new GedcomReader(gedcomFileName); XmlDocument doc = new XmlDocument(); doc.Load(gr); gr.Close(); if (args.Length > 3 && args[2].Equals("-s")) { xsltFileName = args[3]; XslTransform tx = new XslTransform(); tx.Load(xsltFileName); FileStream fs = new FileStream(outputFileName, FileMode.Create); tx.Transform(doc, null, fs, null); } else doc.Save(args[1]); } catch(Exception e) { Console.WriteLine("###error: {0}", e.Message); } }
protected void Page_Load(object sender, EventArgs e) { string xslFile = Server.MapPath("DvdList.xsl"); string xmlFile = Server.MapPath("DvdList.xml"); string htmlFile = Server.MapPath("DvdList.htm"); XslTransform transf = new XslTransform(); transf.Load(xslFile); transf.Transform(xmlFile, htmlFile); // Create an XPathDocument. XPathDocument xdoc = new XPathDocument(new XmlTextReader(xmlFile)); // Create an XPathNavigator. XPathNavigator xnav = xdoc.CreateNavigator(); // Transform the XML XmlReader reader = transf.Transform(xnav, null); // Go the the content and write it. reader.MoveToContent(); Response.Write(reader.ReadOuterXml()); reader.Close(); }
private void Images() { // Dataset containing string catname ="Electricals"; ProductImageService.serProdctImage prodimage = new ProductImageService.serProdctImage(); DataSet dataset = prodimage.ProductImage_GetFashImgtwoForHandler(catname); //string x = dataset.GetXml(); string xmlfile = dataset.GetXml(); XslTransform xslt = new XslTransform(); xslt.Load(Server.MapPath("~/xslt/HomeXSLTFile.xslt")); XPathDocument xpathdocument = new XPathDocument(xmlfile); XmlTextWriter writer = new XmlTextWriter(Console.Out); writer.Formatting = Formatting.Indented; xslt.Transform(xpathdocument, null, writer, null); //strstudentDetails = GetHtml(Server.MapPath("~/xsl/studentDetails.xsl"), strXML); //XPathDocument myXPathDoc = new XPathDocument(myXmlFile); //XslCompiledTransform myXslTrans = new XslCompiledTransform(); //myXslTrans.Load(myStyleSheet); //XmlTextWriter myWriter = new XmlTextWriter("result.html", null); //myXslTrans.Transform(myXPathDoc, null, myWriter); }
static void Main () { XmlDocument doc = new XmlDocument (); doc.Load (new FileStream ("test.xsl", FileMode.Open)); XslTransform t = new XslTransform (); t.Load (doc); }
protected virtual void OnConvert (object sender, System.EventArgs e) { XmlDocument xsltdoc = new XmlDocument(); Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("svg2xaml.xslt"); xsltdoc.Load (s); XslTransform t = new XslTransform(); t.Load (xsltdoc); t.Transform (svgFilename, svgFilename + ".xaml"); FileStream file = File.OpenRead(svgFilename + ".xaml"); using (StreamReader sr = new StreamReader (file)) xaml.Append(sr.ReadToEnd ()); file.Close(); RefreshXaml(); }
/// <summary> /// XML ファイルに XSLT を適用。 /// </summary> static void ApplyXsl(string fileName) { string xslName = GetXSlUri(fileName); if(xslName == null) return; xslName = Path.GetDirectoryName(fileName) + @"\" + xslName.Replace('/', '\\'); string htmlName = Path.ChangeExtension(fileName, ".html"); Console.Write("xml : {0}\nxsl : {1}\nhtml:{2}\n\n", fileName, xslName, htmlName); XslTransform xslt = new XslTransform(); xslt.Load(xslName); xslt.Transform(fileName, htmlName); }
} //Main() /// <summary> /// Demonstrates the XslTransform class using two different overloads. /// One returns an XmlReader containing the transform. /// The other stores the transform in an XmlTextWriter. /// </summary> /// <param name="document"></param> /// <param name="stylesheet"></param> public static void ReadTransformWrite(string document, string stylesheet) { StreamReader stream = null; try { string outputFile = Path.GetFileNameWithoutExtension(document) + "_transform.xml"; // XPathDocument stores the target XML in an efficient way for transformation. XPathDocument myXPathDocument = new XPathDocument(document); XslTransform myXslTransform = new XslTransform(); myXslTransform.Load(stylesheet); // Get back the transform results in an XMLReader and output them to the console. XmlReader reader = myXslTransform.Transform(myXPathDocument, null); Console.WriteLine("Input XML file: {0} \nXSL stylesheet: {1}" + nl, document, stylesheet); Console.WriteLine(nl + "Layout of transformed XML content from XML reader:" + nl); OutputXml(reader); // Create an output file to hold the tranform. // Using an intermediate XmlTextWriter instead of the overload of the Transform method // that writes directly to a file allows more control of the formatting. XmlTextWriter writer = new XmlTextWriter(outputFile, null); writer.Formatting = Formatting.Indented; writer.Indentation = 2; myXslTransform.Transform(myXPathDocument, null, writer); writer.Close(); //Output the contents of the tranformed file to the console. Console.WriteLine(nl + "Transformed XML content from file:" + nl); stream = new StreamReader (outputFile); Console.Write(stream.ReadToEnd()); } //try catch (Exception e) { Console.WriteLine ("Exception: {0}", e.ToString()); } //catch finally { if (stream != null) stream.Close(); } //finally } //ReadTransformWrite()
//This will transform xml document using xslt and produce result xml document //and display it public static void Main(string[] args) { try { XPathDocument myXPathDocument = new XPathDocument("C:/Users/user/Desktop/Assignment 4/schema.xml"); XslTransform myXslTransform = new XslTransform(); XmlTextWriter writer = new XmlTextWriter("C:/Users/user/Desktop/Assignment 4/output.html", null); myXslTransform.Load("http://www.public.asu.edu/~sprakas3/dsod/Hotels.xsl"); myXslTransform.Transform(myXPathDocument, null, writer); writer.Close(); StreamReader stream = new StreamReader("C:/Users/user/Desktop/Assignment 4/output.html"); Console.Write("**This is result document**\n\n"); Console.Write(stream.ReadToEnd()); } catch (Exception e) { } }
public static void Main(string[] args) { try { String xmlDoc = "C:\\Path\\To\\Input.xml" String xslDoc = "C:\\Path\\To\\XSLT_Script.xsl" String newDoc = "C:\\Path\\To\\Output.xml" XPathDocument myXPathDocument = new XPathDocument(xmlDoc); XslTransform myXslTransform = new XslTransform(); myXslTransform.Load(xslDoc); myXslTransform.Transform(myXPathDocument, newDoc); } catch (Exception e) { Console.WriteLine ("Exception: {0}", e.ToString()); } }
private void ParseResponse(string response) { XmlDocument doc = null; XslTransform myXslTransform = null; StringWriter sw = null; try { doc = new XmlDocument(); ; myXslTransform = new XslTransform(); sw = new StringWriter(); doc.LoadXml(response); myXslTransform.Load("C:\\Users\\simona.EDUSOFT2\\Documents\\Visual Studio 2013\\WebSites\\WebSite1\\transform.xsl"); myXslTransform.Transform(doc, null, sw); string result = sw.ToString().Replace("xmlns:asp=\"remove\"", "").Replace("<", "<").Replace(">", ">"); Control control = Page.FindControl("MyTable"); if (control != null) { Page.Controls.Remove(control); } Control ctrl = Page.ParseControl(result); Page.Controls.Add(ctrl); MyPanel.Visible = false; } catch { //parsing or loading error displayErrorMessage(errorParsingOrLoading); } finally { sw.Close(); } }
public Validacion() { cadenaOriginal = ""; Sello = new SelloDigital(); xslt1 = new XslTransform(); }
public static void Main(string[] args) { Opts opts = new Opts(); opts.ProcessArgs(args); if (opts.RemainingArguments.Length != 2 && opts.RemainingArguments.Length != 3) { opts.DoHelp(); return; } string datasource, rootentity, stylesheetfile; if (opts.RemainingArguments.Length == 2) { datasource = opts.RemainingArguments[0]; rootentity = null; stylesheetfile = opts.RemainingArguments[1]; } else { datasource = opts.RemainingArguments[0]; rootentity = opts.RemainingArguments[1]; stylesheetfile = opts.RemainingArguments[2]; } XsltArgumentList xsltargs = new XsltArgumentList(); if (opts.param != null) foreach (string p in opts.param) { int eq = p.IndexOf('='); if (eq == -1) { Console.Error.WriteLine("Param arguments must be name=value."); return; } string n = p.Substring(0, eq); string v = p.Substring(eq+1); xsltargs.AddParam(n, "", v); } XmlDocument sty = new XmlDocument(); sty.PreserveWhitespace = true; sty.Load(stylesheetfile); XslTransform t = new XslTransform(); t.Load(sty, null, null); NamespaceManager nsmgr = new NamespaceManager(); // Scan xmlsn: attributes in the stylesheet node. // For all namespaces of the form assembly://assemblyname/TypeName, load in // the methods of that type as extension functions in that namespace. // And add xmlns declarations to nsmgr. foreach (XmlAttribute a in sty.DocumentElement.Attributes) { if (!a.Name.StartsWith("xmlns:")) continue; nsmgr.AddNamespace(a.Value, a.Name.Substring(6)); System.Uri uri = new System.Uri(a.Value); if (uri.Scheme != "assembly") continue; System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(uri.Host); System.Type ty = assembly.GetType(uri.AbsolutePath.Substring(1)); if (ty == null) { Console.Error.WriteLine("Type not found: " + uri); return; } object obj = ty.GetConstructor(new Type[0]).Invoke(new Type[0]); xsltargs.AddExtensionObject(a.Value, obj); } StatementSource source = Store.CreateForInput(datasource); Store model; if (source is Store) model = (Store)source; else model = new MemoryStore(source); XPathNavigator nav; if (rootentity != null) nav = new XPathSemWebNavigator(rootentity, model, nsmgr); else nav = new XPathSemWebNavigator(model, nsmgr); t.Transform(nav, xsltargs, Console.Out, null); }
/// <summary> /// This is where the work is done /// </summary> protected override void ExecuteTask() { _fileSetSummary = CreateSummaryXmlDoc(); foreach (string file in XmlFileSet.FileNames) { XmlDocument source = new XmlDocument(); source.Load(file); XmlNode node = _fileSetSummary.ImportNode(source.DocumentElement, true); _fileSetSummary.DocumentElement.AppendChild(node); } Log(Level.Info, "Generating report..."); try { // ensure destination directory exists if (!ToDir.Exists) { ToDir.Create(); ToDir.Refresh(); } if (Format == ReportFormat.NoFrames) { XslTransform xslTransform = new XslTransform(); XmlResolver resolver = new LocalResXmlResolver(); if (XslFile != null) { xslTransform.Load(LoadStyleSheet(XslFile), resolver); } else { xslTransform.Load(LoadStyleSheet("NUnit-NoFrame.xsl"), resolver); } // xmlReader hold the first transformation XmlReader xmlReader = xslTransform.Transform(_fileSetSummary, _xsltArgs); // i18n XsltArgumentList xsltI18nArgs = new XsltArgumentList(); xsltI18nArgs.AddParam("lang", "", Language); // Load the i18n stylesheet XslTransform xslt = new XslTransform(); xslt.Load(LoadStyleSheet("i18n.xsl"), resolver); XPathDocument xmlDoc; xmlDoc = new XPathDocument(xmlReader); XmlTextWriter writerFinal = new XmlTextWriter( Path.Combine(ToDir.FullName, "index.html"), Encoding.GetEncoding("ISO-8859-1")); // Apply the second transform to xmlReader to final ouput xslt.Transform(xmlDoc, xsltI18nArgs, writerFinal); xmlReader.Close(); writerFinal.Close(); } else { XmlTextReader reader = null; try { // create the index.html StringReader stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" + "<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" + "<xsl:include href=\"NUnit-Frame.xsl\"/>" + "<xsl:template match=\"test-results\">" + " <xsl:call-template name=\"index.html\"/>" + " </xsl:template>" + " </xsl:stylesheet>"); Write(stream, Path.Combine(ToDir.FullName, "index.html")); // create the stylesheet.css stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" + "<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" + "<xsl:include href=\"NUnit-Frame.xsl\"/>" + "<xsl:template match=\"test-results\">" + " <xsl:call-template name=\"stylesheet.css\"/>" + " </xsl:template>" + " </xsl:stylesheet>"); Write(stream, Path.Combine(ToDir.FullName, "stylesheet.css")); // create the overview-summary.html at the root stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" + "<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" + "<xsl:include href=\"NUnit-Frame.xsl\"/>" + "<xsl:template match=\"test-results\">" + " <xsl:call-template name=\"overview.packages\"/>" + " </xsl:template>" + " </xsl:stylesheet>"); Write(stream, Path.Combine(ToDir.FullName, "overview-summary.html")); // create the allclasses-frame.html at the root stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" + "<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" + "<xsl:include href=\"NUnit-Frame.xsl\"/>" + "<xsl:template match=\"test-results\">" + " <xsl:call-template name=\"all.classes\"/>" + " </xsl:template>" + " </xsl:stylesheet>"); Write(stream, Path.Combine(ToDir.FullName, "allclasses-frame.html")); // create the overview-frame.html at the root stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" + "<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" + "<xsl:include href=\"NUnit-Frame.xsl\"/>" + "<xsl:template match=\"test-results\">" + " <xsl:call-template name=\"all.packages\"/>" + " </xsl:template>" + " </xsl:stylesheet>"); Write(stream, Path.Combine(ToDir.FullName, "overview-frame.html")); XPathNavigator xpathNavigator = _fileSetSummary.CreateNavigator(); // Get All the test suite containing test-case. XPathExpression expr = xpathNavigator.Compile("//test-suite[(child::results/test-case)]"); XPathNodeIterator iterator = xpathNavigator.Select(expr); while (iterator.MoveNext()) { // output directory string path = ""; XPathNavigator xpathNavigator2 = iterator.Current; string testSuiteName = iterator.Current.GetAttribute("name", ""); // Get get the path for the current test-suite. XPathNodeIterator iterator2 = xpathNavigator2.SelectAncestors("", "", true); string parent = ""; int parentIndex = -1; while (iterator2.MoveNext()) { string directory = iterator2.Current.GetAttribute("name", ""); if (directory != "" && directory.IndexOf(".dll") < 0) { path = directory + "/" + path; } if (parentIndex == 1) { parent = directory; } parentIndex++; } // resolve to absolute path path = Path.Combine(ToDir.FullName, path); // ensure directory exists if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // Build the "testSuiteName".html file // Correct MockError duplicate testName ! // test-suite[@name='MockTestFixture' and ancestor::test-suite[@name='Assemblies'][position()=last()]] stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" + "<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" + "<xsl:include href=\"NUnit-Frame.xsl\"/>" + "<xsl:template match=\"/\">" + " <xsl:for-each select=\"//test-suite[@name='" + testSuiteName + "' and ancestor::test-suite[@name='" + parent + "'][position()=last()]]\">" + " <xsl:call-template name=\"test-case\">" + " <xsl:with-param name=\"dir.test\">" + String.Join(".", path.Split('/')) + "</xsl:with-param>" + " </xsl:call-template>" + " </xsl:for-each>" + " </xsl:template>" + " </xsl:stylesheet>"); Write(stream, Path.Combine(path, testSuiteName + ".html")); Log(Level.Debug, "dir={0} Generating {1}.html", path, testSuiteName); } } finally { Log(Level.Debug, "Processing of stream complete."); // Finished with XmlTextReader if (reader != null) { reader.Close(); } } } } catch (Exception ex) { throw new BuildException("Failure generating report.", Location, ex); } }
// -------------------------------------------------------------------------------------------------------------- // LoadXSL_Resolver // ------------------------------------------------------------------------------------------------------------- public int LoadXSL_Resolver(string _strXslFile, XmlResolver xr, InputType inputType, ReaderType readerType) { _strXslFile = FullFilePath(_strXslFile); #pragma warning disable 0618 xslt = new XslTransform(); #pragma warning restore 0618 switch (inputType) { case InputType.URI: _output.WriteLine("Loading style sheet as URI {0}", _strXslFile); xslt.Load(_strXslFile, xr); break; case InputType.Reader: switch (readerType) { case ReaderType.XmlTextReader: XmlTextReader trTemp = new XmlTextReader(_strXslFile); try { _output.WriteLine("Loading style sheet as XmlTextReader {0}", _strXslFile); xslt.Load(trTemp, xr); } catch (Exception ex) { throw (ex); } finally { if (trTemp != null) { trTemp.Dispose(); } } break; case ReaderType.XmlNodeReader: XmlDocument docTemp = new XmlDocument(); docTemp.Load(_strXslFile); XmlNodeReader nrTemp = new XmlNodeReader(docTemp); try { _output.WriteLine("Loading style sheet as XmlNodeReader {0}", _strXslFile); xslt.Load(nrTemp, xr); } catch (Exception ex) { throw (ex); } finally { if (nrTemp != null) { nrTemp.Dispose(); } } break; case ReaderType.XmlValidatingReader: default: #pragma warning disable 0618 XmlValidatingReader vrTemp = new XmlValidatingReader(new XmlTextReader(_strXslFile)); #pragma warning restore 0618 vrTemp.ValidationType = ValidationType.None; vrTemp.EntityHandling = EntityHandling.ExpandEntities; try { _output.WriteLine("Loading style sheet as XmlValidatingReader {0}", _strXslFile); xslt.Load(vrTemp, xr); } catch (Exception ex) { throw (ex); } finally { if (vrTemp != null) { vrTemp.Dispose(); } } break; } break; case InputType.Navigator: #pragma warning disable 0618 XmlValidatingReader xrLoad = new XmlValidatingReader(new XmlTextReader(_strXslFile)); #pragma warning restore 0618 XPathDocument xdTemp = new XPathDocument(xrLoad, XmlSpace.Preserve); xrLoad.Dispose(); _output.WriteLine("Loading style sheet as Navigator {0}", _strXslFile); xslt.Load(xdTemp, xr); break; } return(1); }
public static void Main(string[] args) { if (args.Length == 0) { Console.Error.WriteLine("Specify 'daily' or 'weekly' or 'test' as the command-line argument."); return; } DateTime startTime = DateTime.Now; int emailupdatesfreq = 0; bool testing = false; if (args[0] == "daily") { emailupdatesfreq = 1; } else if (args[0] == "weekly") { emailupdatesfreq = 2; } else if (args[0] == "test") { testing = true; } else { Console.Error.WriteLine("Specify 'daily' or 'weekly' as the command-line argument."); return; } AppModule.InitData(false); XPD.Database.SingleThreadedConnection = true; // Load watchevents stylesheet XmlDocument stylesheet = new XmlDocument(); stylesheet.Load("/home/govtrack/website/users/watchevents.xsl"); // Add a namespace node to load our extension object stylesheet.DocumentElement.SetAttribute("xmlns:govtrack-emailupdates", "assembly://GovTrackEmailUpdates/GovTrack.Web.EmailUpdates,GovTrackEmailUpdates"); // Add an xsl:variable node to load in the events XmlElement var = stylesheet.CreateElement("xsl", "variable", "http://www.w3.org/1999/XSL/Transform"); stylesheet.DocumentElement.AppendChild(var); var.SetAttribute("name", "events"); var.SetAttribute("select", "govtrack-emailupdates:GetEvents()"); // Add an xsl:variable node to load in the monitors var = stylesheet.CreateElement("xsl", "variable", "http://www.w3.org/1999/XSL/Transform"); stylesheet.DocumentElement.AppendChild(var); var.SetAttribute("name", "monitors"); var.SetAttribute("select", "govtrack-emailupdates:GetMonitors()"); // Add an xsl:output node XmlElement output = stylesheet.CreateElement("xsl", "output", "http://www.w3.org/1999/XSL/Transform"); stylesheet.DocumentElement.AppendChild(output); output.SetAttribute("method", "html"); output.SetAttribute("encoding", "utf-8"); // Load in extension objects XsltArgumentList xsltargs = new XsltArgumentList(); foreach (DictionaryEntry ext in XPD.XSLTPipeline.LoadExtensions(stylesheet)) { xsltargs.AddExtensionObject((string)ext.Key, ext.Value); } // Load the transform and the template XslTransform transform = new XslTransform(); transform.Load(stylesheet, null, null); string announcetext = ""; string announcefile = "/home/govtrack/emailupdates-announce.html"; if (File.Exists(announcefile)) { using (StreamReader reader = new StreamReader(announcefile)) announcetext = reader.ReadToEnd(); } List <int> users = new List <int>(); if (testing) { users.AddRange(new int[] { 9 }); } else { foreach (int uid in Util.Database.DBSelectVector("users", "id", new Database.SpecEQ("emailupdates", emailupdatesfreq))) { users.Add(uid); } } users.Sort(); int consecfailures = 0; foreach (int userid in users) { //if (userid <= 52466) continue; CurrentUserId = userid; TableRow user = Util.Database.DBSelectID("users", CurrentUserId, "email, monitors, emailupdates_last, CONVERT(md5(email) USING latin1) as emailhash"); Console.WriteLine(userid + "\t" + user["email"]); HadEvents = false; GetEventsInternal(testing); if (!HadEvents) { if (!testing) { continue; } else { Console.WriteLine("\tThere are no events to send but since we're testing we'll send anyway."); } } Console.WriteLine(userid + "\t" + user["email"]); string textpart = null, htmlpart = null; foreach (string format in new string[] { "text", "html" }) { StringWriter writer = new StringWriter(); if (format == "html") { writer.WriteLine("<html>"); writer.WriteLine("<head>"); writer.WriteLine("<style>"); writer.WriteLine("\tbody { font-family: sans-serif; }"); writer.WriteLine("\t.date { font-size: 90%; color: #AA9999; font-weight: bold; }"); writer.WriteLine("\t.welcome { font-family: Verdana; font-size: 90%; text-align: justify; line-height: 155% } "); writer.WriteLine("\t.welcome a { font-weight: bold; }"); writer.WriteLine("\ta.light { font-weight: normal; text-decoration: none; color: #444488; }"); writer.WriteLine("\ta.light:hover { text-decoration: underline }"); writer.WriteLine("</style>"); writer.WriteLine("</head>"); writer.WriteLine("<body>"); writer.WriteLine("<img src=\"http://www.govtrack.us/perl/emailupdate_trackback.cgi?userid=" + userid + "&emailhash=" + user["emailhash"] + "×tamp=" + Util.DateTimeToUnixDate(DateTime.Now) + "\" width=0 height=0/>"); } writer.WriteLine(announcetext); writer.WriteLine(Tag("h2", "GovTrack.us Tracked Events Update", format)); writer.WriteLine(Tag("p", "This is your email update from " + Tag("a", "href=\"http://www.govtrack.us\"", "www.GovTrack.us", format) + ". " + "To change your email updates settings including to unsubscribe, go to your " + (format == "html" ? @"<a href=""http://www.govtrack.us/users/yourmonitors.xpd"">account settings</a> page" : "account settings page at <http://www.govtrack.us/users/yourmonitors.xpd>" ) + "." , format)); writer.WriteLine(); try { writer.WriteLine((format == "html" ? "<p>" : "") + "You are currently monitoring: "); if (user["monitors"] == null) { continue; } ArrayList monitors = Login.ParseMonitors((string)user["monitors"]); bool firstm = true; foreach (string mon in monitors) { Monitor m = Monitor.FromString(mon); if (m == null) { continue; } if (!firstm) { writer.Write(", "); } firstm = false; writer.Write(m.Display()); } writer.WriteLine("." + (format == "html" ? "</p>" : "")); writer.WriteLine(); XmlDocument template = new XmlDocument(); template.LoadXml("<watchevents format='" + format + "'/>"); transform.Transform(template, xsltargs, writer, null); } catch (Exception e) { Console.WriteLine("There was an error sending email updates for user " + user["email"] + "\n" + e + "\n"); continue; } if (format == "html") { writer.WriteLine("<hr>"); } writer.WriteLine(Tag("p", @"""The right of representation in the legislature [is] a right inestimable to [the people], and formidable to tyrants only."" --" + Tag("a", @"href=""http://etext.virginia.edu/jefferson/quotations/""", "Thomas Jefferson", format) + ": Declaration of Independence, 1776.", format)); if (format == "html") { writer.WriteLine("</body>"); writer.WriteLine("</html>"); } if (format == "text") { textpart = writer.ToString(); } if (format == "html") { htmlpart = writer.ToString(); } } // format if (textpart == null || htmlpart == null) { continue; } if (testing && userid != 9) { continue; // double check! } Console.WriteLine(" - content"); /* DotNetOpenMail * EmailMessage emailMessage = new EmailMessage(); * emailMessage.EnvelopeFromAddress = new EmailAddress("automated+uid_" + userid + "@govtrack.us"); * emailMessage.FromAddress = new EmailAddress("*****@*****.**", "GovTrack.us"); * emailMessage.AddToAddress(new EmailAddress((string)user["email"])); * emailMessage.Subject = "GovTrack.us Tracked Events for " + DateRange; * emailMessage.TextPart = new TextAttachment(textpart); * emailMessage.HtmlPart = new HtmlAttachment(htmlpart); * emailMessage.AddCustomHeader("Precedence", "bulk"); */ MailMessage emailMessage = new MailMessage(); emailMessage.From = new MailAddress("automated+uid_" + userid + "@govtrack.us", "GovTrack.us"); emailMessage.To.Add(new MailAddress((string)user["email"])); emailMessage.Subject = "GovTrack.us Tracked Events for " + DateRange; emailMessage.Body = textpart; emailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(htmlpart, null, "text/html")); emailMessage.Headers["Precedence"] = "bulk"; // Try sending six times, breaking 3 seconds // between attempts. int numAttempts = 0; while (true) { numAttempts++; if (numAttempts == 6) { consecfailures++; break; } try { Console.WriteLine(" - send"); //emailMessage.Send(new SmtpServer("localhost")); new SmtpClient("localhost").Send(emailMessage); consecfailures = 0; break; } catch (System.Net.Sockets.SocketException e) { Console.WriteLine(e); System.Threading.Thread.Sleep(3 * 1000); } catch (DotNetOpenMail.MailException e) { Console.WriteLine(e); System.Threading.Thread.Sleep(3 * 1000); } catch (Exception e) { Console.WriteLine(e); consecfailures++; break; } } if (consecfailures == 5) { throw new Exception("Failed to send 5 messages in a row. Aborting."); } if (!testing) { // Update the user's emailupdates_last field. Hashtable update_last_date = new Hashtable(); update_last_date["emailupdates_last"] = Util.DateTimeToUnixDate(EndDate); Util.Database.DBUpdateID("users", userid, update_last_date); } Console.WriteLine(" - done"); NumEmails++; System.Threading.Thread.Sleep(200); } Console.WriteLine("{0} emails: {1}, time to send: {2}", args[0], NumEmails, DateTime.Now - startTime); }
private void Button_Click_3(object sender, RoutedEventArgs e) { try { XslTransform xsltransform = new XslTransform(); xsltransform.Load("Transform.xslt"); xsltransform.Transform("Interface1.usi", "Interface11.xaml", null); XslTransform xsltransform2 = new XslTransform(); xsltransform2.Load("Transform2.xslt"); xsltransform2.Transform("Interface11.xaml", "Interface12.xaml", null); StreamReader stringReader = new StreamReader("Interface12.xaml"); XmlReader xmlReader = XmlReader.Create(stringReader); win1 = (Window)XamlReader.Load(xmlReader); win1.Show(); win1.Topmost = true; xsltransform.Load("Transform.xslt"); xsltransform.Transform("Interface2.usi", "Interface21.xaml", null); xsltransform2 = new XslTransform(); xsltransform2.Load("Transform2.xslt"); xsltransform2.Transform("Interface21.xaml", "Interface22.xaml", null); stringReader = new StreamReader("Interface22.xaml"); xmlReader = XmlReader.Create(stringReader); win2 = (Window)XamlReader.Load(xmlReader); win2.Show(); win2.Topmost = true; Button buttonLancerEx3 = (Button)this.FindName("lancerex3"); buttonLancerEx3.IsEnabled = true; ListBox lb = (ListBox)win1.FindName("listbox_component_19"); if (lb != null) { lb.SelectionChanged += new SelectionChangedEventHandler(ListBox1_SelectionChanged); } } catch (ParserException e2) { if (win != null) { win.Close(); } RichTextBox textDebug = (RichTextBox)this.FindName("textDebug"); textDebug.AppendText("Parser: " + e2.Message + "\n"); } catch (InterpreterException e2) { if (win != null) { win.Close(); } RichTextBox textDebug = (RichTextBox)this.FindName("textDebug"); textDebug.AppendText("Interpreter: " + e2.Message + "\n"); } catch (Exception e2) { if (win != null) { win.Close(); } RichTextBox textDebug = (RichTextBox)this.FindName("textDebug"); textDebug.AppendText("Erreur inconnue: " + e2.Message + "\n"); System.Console.WriteLine(e2.Message); System.Console.WriteLine(e2.StackTrace); } }
public void GetReady() { xslt = new XslTransform(); }
/// <summary> /// Obtains the content of the web part. /// </summary> /// <param name="partData">The part data.</param> /// <returns></returns> private string ObtainWebPartContent(WebPart partData) { string content = null; if ((partData.ContentLink != null) && (partData.ContentLink.Length > 0)) { content = FetchNetworkContent(partData.ContentLink); } if (content == null) { content = partData.Content; } if ((partData.ContentType == 1) || (partData.ContentType == 2)) { return("<font color=red><b>Unsupported Web Part Content Format</b></font>"); } if (partData.ContentType == 3) { XmlDocument document = new XmlDocument(); document.LoadXml(content); string xslContent = null; if ((partData.XSLLink != null) && (partData.XSLLink.Length > 0)) { xslContent = FetchNetworkContent(partData.XSLLink); } if (xslContent == null) { xslContent = partData.XSL; } StringWriter output = new StringWriter(); #if FW10 XslTransform transform = new XslTransform(); transform.Load(new XmlTextReader(new StringReader(xslContent))); transform.Transform(document, null, output); #else #if FW11 XslTransform transform = new XslTransform(); transform.Load(new XmlTextReader(new StringReader(xslContent)), new XmlUrlResolver(), new Evidence()); transform.Transform(document, null, output, new XmlUrlResolver()); #else // setup and perform the XSLT transformation XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(new XmlTextReader(new StringReader(xslContent))); xslt.Transform(document, null, output); #endif #endif content = output.ToString(); } return(content); }
public XsltTransformer(string stylesheetFilename) { xslTransform = new XslTransform(); xslTransform.Load(stylesheetFilename, null); }
/// <summary> /// Exports dataset into excel format /// </summary> /// <param name="dsExport">The DataSet want to export</param> /// <param name="sHeaders">The headers of DataTable</param> /// <param name="sFields">The data fields of DataTable</param> /// <param name="fileName">The filename of excel</param> private void ExportWithXSLT(DataSet dsExport, string[] sHeaders, string[] sFields, string fileName) { try { //Appending Headers response.Clear(); response.Buffer = true; response.ContentType = "application/vnd.ms-excel"; response.ContentEncoding = System.Text.Encoding.Default; //response.AppendHeader("content-disposition", "attachment; filename="+"测试.xls"); response.AppendHeader("content-disposition", "attachment; filename=" +fileName+".xls"); //XSLT to use for transforming this dataset MemoryStream stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Unicode); CreateStylesheet(writer, sHeaders, sFields); //Create the Stylesheet writer.Flush(); stream.Seek(0, SeekOrigin.Begin); XmlDocument xmlDoc = new XmlDataDocument(dsExport); XslTransform xslTran = new XslTransform(); xslTran.Load(new XmlTextReader(stream), null, null); System.IO.StringWriter sw = new StringWriter(); xslTran.Transform(xmlDoc, null, sw, null); //Write out the content response.Write(sw.ToString()); sw.Close(); writer.Close(); stream.Close(); response.End(); } catch (ThreadAbortException ex) { string ErrMsg = ex.Message; } catch (Exception ex) { throw ex; } }
public void Transform(string modelFilePath) { StreamReader sr; string foDoc; MemoryStream ms = new MemoryStream(); XmlResolver resolver = new XmlUrlResolver(); resolver.Credentials = CredentialCache.DefaultCredentials; XmlDocument doc = new XmlDocument(); doc.XmlResolver = resolver; doc.Load(modelFilePath); XslTransform transform = new XslTransform(); transform.Load(this.stylesheetFilesPath + Path.DirectorySeparatorChar + "PdfRtfExport.xsl", resolver); XsltArgumentList al = new XsltArgumentList(); AssemblyName an = this.GetType().Assembly.GetName(); al.AddParam("version", "", an.Version.ToString(3)); al.AddParam("outputType", "", "withLink"); al.AddParam("description", "", this.localizer.GetValue("Globals", "Description")); al.AddParam("notes", "", this.localizer.GetValue("Globals", "Notes")); al.AddParam("relatedDocs", "", this.localizer.GetValue("Globals", "RelatedDocuments")); al.AddParam("model", "", this.localizer.GetValue("Globals", "Model")); al.AddParam("actor", "", this.localizer.GetValue("Globals", "Actor")); al.AddParam("goals", "", this.localizer.GetValue("Globals", "Goals")); al.AddParam("useCase", "", this.localizer.GetValue("Globals", "UseCase")); al.AddParam("package", "", this.localizer.GetValue("Globals", "Package")); al.AddParam("actors", "", this.localizer.GetValue("Globals", "Actors")); al.AddParam("useCases", "", this.localizer.GetValue("Globals", "UseCases")); al.AddParam("packages", "", this.localizer.GetValue("Globals", "Packages")); al.AddParam("summary", "", this.localizer.GetValue("Globals", "Summary")); al.AddParam("glossary", "", this.localizer.GetValue("Globals", "Glossary")); al.AddParam("glossaryItem", "", this.localizer.GetValue("Globals", "GlossaryItem")); al.AddParam("preconditions", "", this.localizer.GetValue("Globals", "Preconditions")); al.AddParam("postconditions", "", this.localizer.GetValue("Globals", "Postconditions")); al.AddParam("openIssues", "", this.localizer.GetValue("Globals", "OpenIssues")); al.AddParam("flowOfEvents", "", this.localizer.GetValue("Globals", "FlowOfEvents")); al.AddParam("prose", "", this.localizer.GetValue("Globals", "Prose")); al.AddParam("requirements", "", this.localizer.GetValue("Globals", "Requirements")); al.AddParam("details", "", this.localizer.GetValue("Globals", "Details")); al.AddParam("priority", "", this.localizer.GetValue("Globals", "Priority")); al.AddParam("status", "", this.localizer.GetValue("Globals", "Status")); al.AddParam("level", "", this.localizer.GetValue("Globals", "Level")); al.AddParam("complexity", "", this.localizer.GetValue("Globals", "Complexity")); al.AddParam("implementation", "", this.localizer.GetValue("Globals", "Implementation")); al.AddParam("assignedTo", "", this.localizer.GetValue("Globals", "AssignedTo")); al.AddParam("release", "", this.localizer.GetValue("Globals", "Release")); al.AddParam("activeActors", "", this.localizer.GetValue("Globals", "ActiveActors")); al.AddParam("primary", "", this.localizer.GetValue("Globals", "Primary")); al.AddParam("history", "", this.localizer.GetValue("Globals", "History")); al.AddParam("statusNodeSet", "", this.localizer.GetNodeSet("cmbStatus", "Item")); al.AddParam("levelNodeSet", "", this.localizer.GetNodeSet("cmbLevel", "Item")); al.AddParam("complexityNodeSet", "", this.localizer.GetNodeSet("cmbComplexity", "Item")); al.AddParam("implementationNodeSet", "", this.localizer.GetNodeSet("cmbImplementation", "Item")); al.AddParam("historyTypeNodeSet", "", this.localizer.GetNodeSet("HistoryType", "Item")); transform.Transform(doc, al, ms, resolver); ms.Position = 0; sr = new StreamReader(ms, Encoding.UTF8); foDoc = sr.ReadToEnd(); sr.Close(); ms.Close(); this.XmlToPdf(foDoc, this.pdfFilesPath); }
/// <summary> /// Loads information about all the bibliography styles. /// </summary> /// <param name="styleDir"> /// Directory containing the Word bibliography styles. /// </param> /// <param name="worker"> /// Background worker thread on which this function is run. This parameter /// is required if progress should be reported. /// </param> public static Dictionary <string, string> LoadBibliographyStylesInformation(string styleDir, BackgroundWorker worker) { // Place to store the mapping between retrieved style names and style paths. Dictionary <string, string> result = new Dictionary <string, string>(); // Collection of OfficeStyleKeys. Those are predefined styles of which the // name can be localized by Microsoft. Dictionary <string, string> OfficeStyleKeys = new Dictionary <string, string>(10); OfficeStyleKeys.Add("APA", "APA"); OfficeStyleKeys.Add("CHICAGO", "Chicago"); OfficeStyleKeys.Add("GB7714", "GB7714"); OfficeStyleKeys.Add("GOSTNS", "Gost - Name Sort"); OfficeStyleKeys.Add("GOSTTS", "Gost - Title Sort"); OfficeStyleKeys.Add("ISO690", "ISO 690 - First Element and Date"); OfficeStyleKeys.Add("ISO690NR", "ISO 690 - Numerical Reference"); OfficeStyleKeys.Add("MLA", "MLA"); OfficeStyleKeys.Add("SIST02", "SIST02"); OfficeStyleKeys.Add("TURABIAN", "Turabian"); // Variable for XSL transformations. Although deprecated, this is a lot // faster than XslCompiledTransform. XslTransform xslt = new XslTransform(); // Variable for storing the xml fragment that needs transformation. XmlDocument doc = new XmlDocument(); // Report progress. if (worker != null) { worker.ReportProgress(0, "Building list of *.xsl files..."); } // Retrieve a list of all possible styles in the directory. // Note: Directory.GetFiles(styleDir, "*.xsl") might give // unwanted results on a case sensitive OS! List <string> styles = new List <string>(); // Get all the files in the directory. string[] files = Directory.GetFiles(styleDir, "*"); for (int i = 0; i < files.Length; i++) { FileInfo fi = new FileInfo(files[i]); // Add the file to the list if the lower case variant // of its extension is '.xsl'. if (fi.Extension.ToLowerInvariant() == ".xsl") { styles.Add(files[i]); } } // Variable containing the maximum number of styles. int styleMax = styles.Count; // Variable containing the number of styles processed so far. int styleCnt = 0; // Handle all styles in the directory. foreach (string stylePath in styles) { // Used for storing the result of a transformation. StringBuilder sb = new StringBuilder(); TextWriter tw = new StringWriter(sb, CultureInfo.InvariantCulture); try { // Load the style. xslt.Load(stylePath); // Load document for the transformation. doc.LoadXml("<b:StyleName xmlns:b=\"" + BibliographyNS + "\"/>"); // Transform the document. xslt.Transform(doc, null, tw); // Get the result of the transformation. string styleName = sb.ToString(); // If the result is empty, try going for the OfficeStyleKey instead of the StyleName. if (String.IsNullOrEmpty(styleName) == true) { // Load document for the transformation. doc.LoadXml("<b:OfficeStyleKey xmlns:b=\"" + BibliographyNS + "\"/>"); // Transform the document. xslt.Transform(doc, null, tw); // Get the actual name based on the transformation result. if (OfficeStyleKeys.ContainsKey(sb.ToString().ToUpperInvariant()) == true) { styleName = OfficeStyleKeys[sb.ToString().ToUpperInvariant()]; } } // If the result is not empty, add to the map. if (String.IsNullOrEmpty(styleName) == false) { // Check if the name is not yet in the result map. if (result.ContainsKey(styleName) == false) { result.Add(styleName, stylePath); } else { // If the style name is already in the map, add the first possible // indexer after it between brackets. int cnt = 2; while (result.ContainsKey(styleName + " (" + cnt + ")") == true) { cnt++; } styleName += " (" + cnt + ")"; result.Add(styleName, stylePath); } } } catch { // Ignore all exceptions, move to the next one. } finally { // One more style was processed (not necessarily correct). styleCnt += 1; // Report progress if required. if (worker != null) { FileInfo fi = new FileInfo(stylePath); worker.ReportProgress((100 * styleCnt / styleMax), "Processed " + fi.Name + "..."); } } } return(result); }
private static void Generate(XmlDocument source, XslTransform transform, XsltArgumentList args, string output, XslTransform template) { using (TextWriter textwriter = new StreamWriter(new FileStream(output, FileMode.Create))) { XmlTextWriter writer = new XmlTextWriter(textwriter); writer.Formatting = Formatting.Indented; writer.Indentation = 2; writer.IndentChar = ' '; try { XmlDocument intermediate = new XmlDocument(); intermediate.PreserveWhitespace = true; intermediate.Load(transform.Transform(source, args, new ManifestResourceResolver(opts.source))); template.Transform(intermediate, new XsltArgumentList(), new XhtmlWriter(writer), null); } catch (Exception e) { throw new ApplicationException("An error occured while generating " + output, e); } } }
private static int CreateDocumentation(string xmlDocPath, string pathOutput, string baseUrl) { XDocument doc; using (var fs = new FileStream(xmlDocPath, FileMode.Open, FileAccess.Read)) { doc = XDocument.Load(fs); } string docContent = doc.ToString(); XslTransform xslt = new XslTransform(); xslt.Load(ExtFiles.Get("markdown.xslt")); XPathDocument xpathdocument = new XPathDocument(new StringReader(docContent)); var stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); xslt.Transform(xpathdocument, null, writer, null); stream.Position = 0; XDocument xdoc = XDocument.Load(stream); writer.Close(); if (!Directory.Exists(pathOutput)) { Directory.CreateDirectory(pathOutput); } var contentStdlibPath = Path.Combine(pathOutput, "stdlib"); Directory.CreateDirectory(contentStdlibPath); var tocBuilder = new StringBuilder(); var knownNodes = new HashSet <string>(); if (baseUrl == null) { baseUrl = ""; } using (var layout = new StreamReader(ExtFiles.Get("toc_layout.md"))) { var content = layout.ReadToEnd(); tocBuilder.Append(content); tocBuilder.Replace("$base_url$", baseUrl); var matches = Regex.Matches(content, @"(?=\S)\[(.*)\]\S"); foreach (Match match in matches) { var uri = match.Groups[1].Value; knownNodes.Add(uri); } } using (var tocWriter = new StreamWriter(Path.Combine(pathOutput, "stdlib.md"))) { tocWriter.Write(tocBuilder.ToString()); tocBuilder.Clear(); foreach (var fileNode in xdoc.Root.Elements("document")) { string name = fileNode.Attribute("href").Value.Replace(".md", ""); string link = name.Replace(" ", "%20"); string path = Path.Combine(contentStdlibPath, fileNode.Attribute("href").Value); using (var file = new FileStream(path, FileMode.Create)) using (var fileWriter = new StreamWriter(file)) { fileWriter.Write(fileNode.Value); } if (!knownNodes.Contains(name)) { tocWriter.WriteLine("* [{0}]({1}/{2})", name, baseUrl, link); } } } return(0); }
/// <summary> /// Loads information about all the bibliography styles. /// </summary> /// <param name="worker"> /// Background worker thread on which this function is run. This parameter /// is required if progress should be reported. /// </param> public static Dictionary <string, string> LoadBibliographyStylesInformation(BackgroundWorker worker) { // Place to store the mapping between retrieved style names and style paths. Dictionary <string, string> result = new Dictionary <string, string>(); // Collection of OfficeStyleKeys. Those are predefined styles of which the // name can be localized by Microsoft. Dictionary <string, string> OfficeStyleKeys = new Dictionary <string, string>(10); OfficeStyleKeys.Add("APA", "APA"); OfficeStyleKeys.Add("CHICAGO", "Chicago"); OfficeStyleKeys.Add("GB7714", "GB7714"); OfficeStyleKeys.Add("GOSTNS", "Gost - Name Sort"); OfficeStyleKeys.Add("GOSTTS", "Gost - Title Sort"); OfficeStyleKeys.Add("ISO690", "ISO 690 - First Element and Date"); OfficeStyleKeys.Add("ISO690NR", "ISO 690 - Numerical Reference"); OfficeStyleKeys.Add("MLA", "MLA"); OfficeStyleKeys.Add("SIST02", "SIST02"); OfficeStyleKeys.Add("TURABIAN", "Turabian"); // Variable for XSL transformations. Although deprecated, this is a lot // faster than XslCompiledTransform. XslTransform xslt = new XslTransform(); // Variable for storing the xml fragment that needs transformation. XmlDocument doc = new XmlDocument(); // Get the path to the directory containing the bibliography styles. string styleDir = GetBibliographyStylesPath(); // Report progress if required. if (worker != null) { // Report that the style directory was found (0% completed). worker.ReportProgress(0, "Found style directory at " + styleDir); } // Variable containing the number of styles. int styleMax = Directory.GetFiles(styleDir, "*.xsl").Length; // Variable containing the number of styles processed so far. int styleCnt = 0; // Handle all styles in the directory. foreach (string stylePath in Directory.GetFiles(styleDir, "*.xsl")) { // Used for storing the result of a transformation. StringBuilder sb = new StringBuilder(); TextWriter tw = new StringWriter(sb); try { // Load the style. xslt.Load(stylePath); // Load document for the transformation. doc.LoadXml("<b:StyleName xmlns:b=\"http://schemas.openxmlformats.org/officeDocument/2006/bibliography\"/>"); // Transform the document. xslt.Transform(doc, null, tw); // Get the result of the transformation. string styleName = sb.ToString(); // If the result is empty, try going for the OfficeStyleKey instead of the StyleName. if (styleName == "") { // Load document for the transformation. doc.LoadXml("<b:OfficeStyleKey xmlns:b=\"http://schemas.openxmlformats.org/officeDocument/2006/bibliography\"/>"); // Transform the document. xslt.Transform(doc, null, tw); // Get the actual name based on the transformation result. styleName = OfficeStyleKeys[sb.ToString()]; } // If the result is not empty, add to the map. if (styleName != "") { // Check if the name is not yet in the result map. if (result.ContainsKey(styleName) == false) { result.Add(styleName, stylePath); } else { // If the style name is already in the map, add the first possible // indexer after it between brackets. int cnt = 2; while (result.ContainsKey(styleName + " (" + cnt + ")") == true) { cnt++; } styleName += " (" + cnt + ")"; result.Add(styleName, stylePath); } } } catch (Exception) { } finally { // One more style was processed (not necessarily correct). styleCnt += 1; // Report progress if required. if (worker != null) { FileInfo fi = new FileInfo(stylePath); worker.ReportProgress((100 * styleCnt / styleMax), fi.Name); } } } return(result); }
private void DoTransform(string xsl, string xml, string output) { try { #if true /// new way /// //Create the XslTransform and load the stylesheet. System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform(); xslt.Load(xsl, System.Xml.Xsl.XsltSettings.TrustedXslt, null); //Load the XML data file. System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(xml); //Create an XmlTextWriter to output to the console. System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(output, System.Text.Encoding.UTF8); writer.Formatting = System.Xml.Formatting.Indented; //Transform the file. xslt.Transform(doc, null, writer); writer.Close(); #if false //Create the XslTransform and load the stylesheet. XslTransform xslt = new XslTransform(); xslt.Load(xsl); //Load the XML data file. XPathDocument doc = new XPathDocument(xml); //Create an XmlTextWriter to output to the console. XmlTextWriter writer = new XmlTextWriter(output, System.Text.Encoding.UTF8); writer.Formatting = Formatting.Indented; //Transform the file. xslt.Transform(doc, null, writer, null); writer.Close(); #endif #else SIL.Utils.XmlUtils.TransformFileToFile(xsl, xml, output); #endif } catch(Exception ee) { System.Diagnostics.Debug.WriteLine(ee.Message); } }
public string[] GenerateDIE() { DataTable DieTb = GetDataDIE(); DataRow Riga = DieTb.Rows[0]; string CodEdi = Riga["codedi"].ToString(); string CodiceSGA = Riga["sga"].ToString(); Stream stream = new MemoryStream(); //creo l'oggetto xml XmlTextWriter writer = new XmlTextWriter(stream, null); //writer.Formatting = Formatting.Indented; writer.WriteStartElement("data"); // writer.WriteElementString("CODICE",ReplaceAccenti(Riga["sga"].ToString().Trim()); string SGA = Riga["codedi"].ToString() + "_" + System.DateTime.Parse(Riga["dataRichiesta"].ToString()).ToString("yy") + "_" + FormatNumber(Riga["sga_count"].ToString()); writer.WriteElementString("CODICE", SGA); writer.WriteElementString("SEDE", Riga["codedi"].ToString()); writer.WriteElementString("PIANO", Riga["piano"].ToString().Replace("°", "\\'b0")); //writer.WriteElementString("DATA",ReplaceAccenti(Riga["dataRichiesta"].ToString()); writer.WriteElementString("DATA", DateTime.Now.ToShortDateString()); writer.WriteElementString("NOMEEDIFICIO", ReplaceAccenti(Riga["edificio"].ToString())); writer.WriteElementString("AMBIENTE", ReplaceAccenti(Riga["ambiente"].ToString())); writer.WriteElementString("SERVIZIO", ReplaceAccenti(Riga["servizio_id"].ToString())); writer.WriteElementString("DESCPROB", ReplaceAccenti(Riga["descrizioneprob"].ToString())); writer.WriteElementString("ID_SEG", ReplaceAccenti(Riga["id_sga_seguito"].ToString())); switch (Riga["id_sga_seguito"].ToString()) { case "3": writer.WriteElementString("ORDINEDEL", Riga["die_del"].ToString()); writer.WriteElementString("ORDINENUM", Riga["die_numero"].ToString()); break; case "4": writer.WriteElementString("MANDIFFDEL", Riga["die_del"].ToString()); break; case "2": writer.WriteElementString("MANPROGDEL", Riga["die_del"].ToString()); break; } writer.WriteElementString("DIETIPINT", Riga["die_tipo_intervento"].ToString()); writer.WriteElementString("N_REG", Riga["die_registro"].ToString()); writer.WriteElementString("MESE", GetMese(Riga["die_mese"].ToString())); writer.WriteElementString("GG_APERTURA", Riga["date_requested"].ToString()); writer.WriteElementString("GG_INTMA", Riga["date_start"].ToString()); writer.WriteElementString("GG_CHIUSURA", Riga["date_end"].ToString()); writer.WriteElementString("NOMEDITTA", Riga["ditta"].ToString()); writer.WriteElementString("TECNICOESECUTORE", Riga["addetto"].ToString()); writer.WriteElementString("TELEFONO", Riga["telefono"].ToString()); writer.WriteElementString("EMAIL", Riga["email"].ToString()); writer.WriteElementString("VAL_ECONOMICA", ""); writer.WriteElementString("TIP_MAN", Riga["tipomanutenzione_id"].ToString()); writer.WriteElementString("COSTO_MAT", Riga["TM"].ToString()); writer.WriteElementString("COSTO_PERS", Riga["TA"].ToString()); double tot = double.Parse(Riga["TM"].ToString()) + double.Parse(Riga["TA"].ToString()); writer.WriteElementString("COSTO_TOT", tot.ToString()); writer.WriteElementString("DICHIARA1", ReplaceAccenti(Riga["die_dichiara1"].ToString())); writer.WriteElementString("DICHIARA2", ReplaceAccenti(Riga["die_dichiara2"].ToString())); int[] CaratteriPerDichiara = new int[] { 108, 108 }; // string [] TmpRighe = DividiInRIghe(ReplaceAccenti(Riga["comments"].ToString(),CaratteriPerDichiara); string [] TmpRighe = DividiParole(ReplaceAccenti(Riga["comments"].ToString()), CaratteriPerDichiara); writer.WriteElementString("DICHIARA", ReplaceAccenti(TmpRighe[0])); writer.WriteElementString("DICHIARA_1", ReplaceAccenti(TmpRighe[1])); int[] CaratteriPerNote = new int[] { 103, 78 }; string [] TmpRighe1 = DividiParole(Riga["die_note"].ToString(), CaratteriPerNote); writer.WriteElementString("DICHIARA_NOTE1", ReplaceAccenti(TmpRighe1[0])); writer.WriteElementString("DICHIARA_NOTE2", ReplaceAccenti(TmpRighe1[1])); writer.WriteElementString("NOME_MA", ReplaceAccenti(Riga["nomimativo"].ToString())); writer.WriteElementString("TEL_MA", Riga["tel"].ToString()); writer.WriteElementString("FAX_MA", Riga["fax"].ToString()); writer.WriteElementString("MOBILE_MA", Riga["mobile"].ToString()); writer.WriteElementString("MAIL_MA", Riga["email_ma"].ToString()); writer.WriteElementString("NOME_SM", Riga["sm_nome"].ToString()); writer.WriteElementString("FIRMA_SM", Riga["sm_firma"].ToString()); writer.WriteElementString("DATA_SM", Riga["sm_data"].ToString()); writer.WriteElementString("NOME_FM", Riga["fm_nome"].ToString()); writer.WriteElementString("FIRMA_FM", Riga["fm_firma"].ToString()); writer.WriteElementString("DATA_FM", Riga["fm_data"].ToString()); writer.WriteEndElement(); writer.Flush(); stream = writer.BaseStream; stream.Position = 0; XPathDocument xmlDoc = new XPathDocument(stream); string XstName = ""; if (Riga["id_progetto"].ToString() == "2") //Vodafone { XstName = "XSLTDIEVod.xslt"; } else { XstName = "XSLTDIE.xslt"; } //carico il file xslt string XsltFilePath = System.Web.HttpContext.Current.Server.MapPath(@"..\XSLT\" + XstName); XslTransform xslt = new XslTransform(); xslt.Load(XsltFilePath); XsltArgumentList args = new XsltArgumentList(); string PathDIE = System.Web.HttpContext.Current.Server.MapPath(@"..\Doc_DB"); PathDIE = Path.Combine(PathDIE, Riga["codedi"].ToString()); if (!Directory.Exists(PathDIE)) { Directory.CreateDirectory(PathDIE); } PathDIE = Path.Combine(PathDIE, this.wr_id.ToString()); if (!Directory.Exists(PathDIE)) { Directory.CreateDirectory(PathDIE); } string FileName = PathDIE + @"\DIE " + CodEdi + " " + FormatNumber(Riga["sga_count"].ToString()) + "-" + System.DateTime.Parse(Riga["dataRichiesta"].ToString()).ToString("yy") + " " + DataCreate + ".rtf"; XmlTextWriter wr = new XmlTextWriter(FileName, null); xslt.Transform(xmlDoc, null, wr, null); wr.Flush(); wr.Close(); stream.Close(); string FileNameDIELast = PathDIE + @"\DIE " + CodEdi + " " + FormatNumber(Riga["sga_count"].ToString()) + "-" + System.DateTime.Parse(Riga["dataRichiesta"].ToString()).ToString("yy") + ".rtf"; if (File.Exists(FileNameDIELast)) { File.Delete(FileNameDIELast); } File.Copy(FileName, FileNameDIELast, true); string FileZip = Path.GetDirectoryName(FileNameDIELast) + @"\" + Path.GetFileNameWithoutExtension(FileNameDIELast) + ".zip"; if (File.Exists(FileZip)) { File.Delete(FileZip); } ZipOutputStream s = new ZipOutputStream(File.Create(FileZip)); s.SetLevel(5); // 0 - store only to 9 - means best compression FileStream fs = File.OpenRead(FileNameDIELast); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(Path.GetFileName(FileNameDIELast)); s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); s.Finish(); s.Close(); string[] doc = new string[2] { FileZip, FileName }; return(doc); }
/// <summary> /// Constructor initializes class. /// </summary> public ExsltTransform() { this.xslTransform = new XslTransform(); }
private void button2_Click(object sender, EventArgs e) { xmlmgmt bar = new xmlmgmt(); requestGetfilestore rgf = new requestGetfilestore(); rgf.location = filestorelocation.local; rgf.annotated = true; rgf.layoutonly = false; request xmlr = new request(); xmlr.domain = domain; xmlr.Item = rgf; response xmlres; xmlres = bar.operation(xmlr); responseFilestore xmlres1; xmlres1 = (responseFilestore)xmlres.Item; // create a writer and open the file TextWriter tw = new StreamWriter("datapower.xml"); string test = xmlres1.Any.Length.ToString(); int test2 = Convert.ToInt32(test); tw.WriteLine("<foo>"); for (int i = 0; i <= test2 - 1; i++) { // write a line of text to the file tw.WriteLine("<foo" + i + ">"); tw.WriteLine(xmlres1.Any[i].InnerXml.ToString()); //tw.WriteLine(xmlres.Item.); tw.WriteLine("</foo" + i + ">"); } tw.WriteLine("</foo>"); // close the stream tw.Close(); XmlDocument xmldoc = new XmlDocument(); //xmldoc.Load(DataPowerFileManager xmldoc.Load("datapower.xml"); XslTransform myXslTrans = new XslTransform(); //myXslTrans.Load("datapower.xslt"); XmlTextReader xsltReader = new XmlTextReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("DataPowerFileManager.DataPower FileSystem Transformations.xslt")); XmlTextWriter myWriter = new XmlTextWriter("result.xml", null); myXslTrans.Load(xsltReader, null, null); myXslTrans.Transform(xmldoc, null, myWriter); myWriter.Close(); xmldoc.Load("result.xml"); //string size = null; //string modified = null; //XmlNodeList list = null; //XmlNodeReader reader = null; //list = xmldoc.GetElementsByTagName("file"); //foreach (XmlNode n in list) //{ // reader = new XmlNodeReader(n); // reader.Read(); // string test = reader.GetAttribute("name"); // modified = n[modified].InnerText; // size = n["size"].InnerText; //do something with s //} //XmlNodeList xnode = xmldoc.SelectNodes(@" /foo/directory[1]/file[*]/@name"); //XmlNode xnode = xmldoc.SelectNodes(@" /foo/directory[1]/file[*]/@name"); //XmlNodeReader nr = new XmlNodeReader(xnode); DataSet ds = new DataSet(); //ds.ReadXml(nr); //dataGridView1.DataSource = ds.Tables[0]; //dataGridView1.Columns[0].Visible = false; System.IO.StringReader sr = new System.IO.StringReader(xmldoc.InnerXml); XPathDocument doc = new XPathDocument(sr); XPathNavigator nav = doc.CreateNavigator(); //XPathExpression expImgSize = nav.Compile(@" /foo/directory[*]/@name"); XPathExpression expImgSize = nav.Compile(@" /foo/directory[1]/file[*]/@name"); XPathNodeIterator iterImageSize = nav.Select(expImgSize); if (iterImageSize != null) { while (iterImageSize.MoveNext()) { string imageSize = iterImageSize.Current.Value; words = imageSize.Split(delimiterChars); //lvDataPower.Items.Add(words[0]); } } try { // SECTION 2. Initialize the TreeView control. treeView2.Nodes.Clear(); treeView2.Nodes.Add(new TreeNode(xmldoc.DocumentElement.Name)); TreeNode tNode = new TreeNode(); tNode = treeView2.Nodes[0]; // SECTION 3. Populate the TreeView with the DOM nodes. AddNode(xmldoc.DocumentElement, tNode); treeView2.ExpandAll(); } catch (XmlException xmlEx) { MessageBox.Show(xmlEx.Message); } catch (Exception ex) { MessageBox.Show(ex.Message); } //textBox1.Text = xmlres1.ToString(); //textBox1.Text = xmlres1.Any[0].InnerXml.ToString(); //treeView1.da }
private void Button_Click_2(object sender, RoutedEventArgs e) { //Console.WriteLine("enter"); if (!isUsi || !isSit) { return; } //Console.WriteLine("enter2"); try { Parser test = new Parser(sitPath, "SyntaxeConcrete.txt"); XslTransform xsltransform = new XslTransform(); xsltransform.Load("Transform.xslt"); String xaml = "1.xaml"; xsltransform.Transform(usiPath, xaml, null); XslTransform xsltransform2 = new XslTransform(); xsltransform2.Load("Transform2.xslt"); String xaml2 = "2.xaml"; xsltransform2.Transform(xaml, xaml2, null); RichTextBox textDebug = (RichTextBox)this.FindName("textDebug"); textDebug.AppendText("Fichier UsiXML transformé en XAML." + "\n"); StreamReader stringReader = new StreamReader(xaml2); XmlReader xmlReader = XmlReader.Create(stringReader); if (win != null) { win.Close(); } win = (Window)XamlReader.Load(xmlReader); stringReader.Close(); win.Show(); win.Topmost = true; textDebug.AppendText("Interface XAML chargée." + "\n"); Tree <Symbol> parse = test.Parse(); textDebug.AppendText("Analyse syntaxique du fichier Sit terminée." + "\n"); inter = new Interpreter(parse, win); textDebug.AppendText("Animation créée." + "\n"); if (clock != null) { clock.Stop(); } clock = new System.Timers.Timer(1000); elapsedTime = 0; clock.Elapsed += new ElapsedEventHandler(OnTimedEvent); clock.Start(); inter.runAnimation(); Button butPrec = (Button)this.FindName("butPrec"); butPrec.IsEnabled = true; Button butPlay = (Button)this.FindName("butPlay"); butPlay.IsEnabled = true; Button butNext = (Button)this.FindName("butNext"); butNext.IsEnabled = true; } catch (ParserException e2) { if (win != null) { win.Close(); } RichTextBox textDebug = (RichTextBox)this.FindName("textDebug"); textDebug.AppendText("Parseur: " + e2.Message + "\n"); } catch (InterpreterException e2) { if (win != null) { win.Close(); } RichTextBox textDebug = (RichTextBox)this.FindName("textDebug"); textDebug.AppendText("Interpreteur: " + e2.Message + "\n"); } catch (Exception e2) { if (win != null) { win.Close(); } RichTextBox textDebug = (RichTextBox)this.FindName("textDebug"); textDebug.AppendText("Erreur inconnue: " + e2.Message + "\n"); } }
/// <summary> /// The Page_Load event handler on this User Control uses /// the Portal configuration system to obtain an xml document /// and xsl/t transform file location. It then sets these /// properties on an <asp:Xml> server control. /// </summary> /// <param name="e"> /// The <see cref="System.EventArgs"/> instance containing the event data. /// </param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); var xmlSetting = this.Settings["XMLsrc"].ToString(); if (xmlSetting.StartsWith("http://") || xmlSetting.StartsWith("https://")) { try { var wr = (HttpWebRequest)WebRequest.Create(xmlSetting); // set the HTTP properties wr.Timeout = 300 * 1000; // milliseconds to seconds // Read the response var resp = wr.GetResponse(); // Stream read the response var stream = resp.GetResponseStream(); if (stream != null) { // Read XML data from the stream // ignore the DTD (resolver null) var reader = new XmlTextReader(stream) { XmlResolver = null }; // Create a new document object var doc = new XmlDocument(); // Create the content of the XML Document from the XML data stream doc.Load(reader); // the XML control to hold the generated XML document this.xml1.Document = doc; } } catch (Exception ex) { this.Controls.Add( new LiteralControl( string.Format( "<br /><span class='Error'>{0}<br />", General.GetString("FILE_NOT_FOUND").Replace("%1%", xmlSetting)))); ErrorHandler.Publish(LogLevel.Error, ex); } } else { var pt = new PortalUrlDataType { Value = this.Settings["XMLsrc"].ToString() }; var xmlsrc = pt.FullPath; if (!string.IsNullOrEmpty(xmlsrc)) { if (File.Exists(this.Server.MapPath(xmlsrc))) { this.xml1.DocumentSource = xmlsrc; // Change - 28/Feb/2003 - Jeremy Esland // Builds cache dependency files list this.ModuleConfiguration.CacheDependency.Add(this.Server.MapPath(xmlsrc)); } else { this.Controls.Add( new LiteralControl( string.Format( "<br /><span class='Error'>{0}<br />", General.GetString("FILE_NOT_FOUND").Replace("%1%", xmlsrc)))); } } } var xslSetting = this.Settings["XSLsrc"].ToString(); if (xslSetting.StartsWith("http://") || xslSetting.StartsWith("https://")) { try { var t = new XslTransform(); t.Load(xslSetting); xml1.Transform = t; } catch (Exception ex) { this.Controls.Add( new LiteralControl( string.Format( "<br /><span class='Error'>{0}<br />", General.GetString("FILE_NOT_FOUND").Replace("%1%", xslSetting)))); ErrorHandler.Publish(LogLevel.Error, ex); } } else { var pt = new PortalUrlDataType { Value = this.Settings["XSLsrc"].ToString() }; var xslsrc = pt.FullPath; if (string.IsNullOrEmpty(xslsrc)) { return; } if (File.Exists(this.Server.MapPath(xslsrc))) { this.xml1.TransformSource = xslsrc; // Change - 28/Feb/2003 - Jeremy Esland // Builds cache dependency files list this.ModuleConfiguration.CacheDependency.Add(this.Server.MapPath(xslsrc)); } else { this.Controls.Add( new LiteralControl( string.Format( "<br /><span class='Error'>{0}<br />", General.GetString("FILE_NOT_FOUND").Replace("%1%", xslsrc)))); } } }
public void directLoad() { try { String path = "C:\\Users\\charly\\Documents\\Visual Studio 2010\\Projects\\Animator\\Animator\\"; //String path = "C:\\Users\\charly\\Documents\\Expression\\Blend 4\\Projects\\Animator\\Animator\\"; //Parser test = new Parser(path + "Tests\\lex\\poll.sit", path + "SyntaxeConcrete.txt"); //Parser test = new Parser(path + "Tests\\lex\\pollTest.sit", path + "SyntaxeConcrete.txt"); //Parser test = new Parser(path + "Tests\\lex\\box.sit", path + "SyntaxeConcrete.txt"); Parser test = new Parser(path + "Tests\\Final\\Interface1.sit", path + "SyntaxeConcrete.txt"); //Parser test = new Parser(path + "Tests\\Final\\Interface2.sit", path + "SyntaxeConcrete.txt"); XslTransform xsltransform = new XslTransform(); xsltransform.Load(path + "Tests\\xsl\\test2\\Transform.xslt"); //xsltransform.Transform(path + "Tests\\xsl\\test2\\Box.usi", path + "Tests\\xsl\\test2\\Box.xaml", null); //xsltransform.Transform(path + "Tests\\xsl\\test2\\Poll.usi", path + "Tests\\xsl\\test2\\Poll.xaml", null); //xsltransform.Transform(path + "Tests\\xsl\\test2\\PollTest.usi", path + "Tests\\xsl\\test2\\PollTest.xaml", null); xsltransform.Transform(path + "Tests\\Final\\Interface1.usi", path + "Tests\\Final\\Interface11.xaml", null); //xsltransform.Transform(path + "Tests\\Final\\Interface2.usi", path + "Tests\\Final\\Interface21.xaml", null); XslTransform xsltransform2 = new XslTransform(); xsltransform2.Load(path + "Tests\\xsl\\test2\\Transform2.xslt"); //xsltransform2.Transform(path + "Tests\\xsl\\test2\\Box.xaml", path + "Tests\\xsl\\test2\\Box2.xaml", null); //xsltransform2.Transform(path + "Tests\\xsl\\test2\\Poll.xaml", path + "Tests\\xsl\\test2\\Poll2.xaml", null); //xsltransform2.Transform(path + "Tests\\xsl\\test2\\PollTest.xaml", path + "Tests\\xsl\\test2\\PollTest2.xaml", null); xsltransform2.Transform(path + "Tests\\Final\\Interface11.xaml", path + "Tests\\Final\\Interface12.xaml", null); //xsltransform2.Transform(path + "Tests\\Final\\Interface21.xaml", path + "Tests\\Final\\Interface22.xaml", null); //StreamReader stringReader = new StreamReader(path + "Tests\\xsl\\test2\\Box2.xaml"); //StreamReader stringReader = new StreamReader(path + "Tests\\xsl\\test2\\Poll2.xaml"); //StreamReader stringReader = new StreamReader(path + "Tests\\xsl\\test2\\PollTest2.xaml"); StreamReader stringReader = new StreamReader(path + "Tests\\Final\\Interface12.xaml"); //StreamReader stringReader = new StreamReader(path + "Tests\\Final\\Interface22.xaml"); XmlReader xmlReader = XmlReader.Create(stringReader); win = (Window)XamlReader.Load(xmlReader); win.Show(); /*PropertyInfo pi = win.GetType().GetProperty("Height"); * pi.SetValue(win, (Double)1500, null); * double value = (double)(pi.GetValue(win, null)); * Console.WriteLine(value);*/ win.Topmost = true; inter = new Interpreter(test.Parse(), win); if (clock != null) { clock.Stop(); } clock = new System.Timers.Timer(1000); clock.Elapsed += new ElapsedEventHandler(OnTimedEvent); clock.Start(); inter.runAnimation(); /*Button btnOk = (Button)win.FindName(inter.getControlEvolutions("button_1").Name); * * if (btnOk != null) * btnOk.Click += new RoutedEventHandler(button1_Click);*/ } catch (ParserException e) { if (win != null) { win.Close(); } RichTextBox textDebug = (RichTextBox)this.FindName("textDebug"); textDebug.AppendText("Parser: " + e.Message + "\n"); }catch (InterpreterException e) { if (win != null) { win.Close(); } RichTextBox textDebug = (RichTextBox)this.FindName("textDebug"); textDebug.AppendText("Interpreter: " + e.Message + "\n"); } catch (Exception e) { if (win != null) { win.Close(); } RichTextBox textDebug = (RichTextBox)this.FindName("textDebug"); textDebug.AppendText("Erreur inconnue: " + e.Message + "\n"); System.Console.WriteLine(e.Message); System.Console.WriteLine(e.StackTrace); } }
protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (InFiles.BaseDirectory == null) { InFiles.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } StringCollection srcFiles = null; if (SrcFile != null) { srcFiles = new StringCollection(); srcFiles.Add(SrcFile.FullName); } else if (InFiles.FileNames.Count > 0) { if (OutputFile != null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1148")), Location); } srcFiles = InFiles.FileNames; } if (srcFiles == null || srcFiles.Count == 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1147")), Location); } if (!XsltFile.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1149"), XsltFile.FullName), Location); } foreach (string srcFile in srcFiles) { string destFile = null; if (OutputFile != null) { destFile = OutputFile.FullName; } if (StringUtils.IsNullOrEmpty(destFile)) { // TODO: use System.IO.Path (gs) // append extension if necessary string ext = Extension.IndexOf(".") > -1 ? Extension : "." + Extension; int extPos = srcFile.LastIndexOf('.'); if (extPos == -1) { destFile = srcFile + ext; } else { destFile = srcFile.Substring(0, extPos) + ext; } destFile = Path.GetFileName(destFile); } FileInfo srcInfo = new FileInfo(srcFile); FileInfo destInfo = new FileInfo(Path.GetFullPath(Path.Combine( DestDir.FullName, destFile))); if (!srcInfo.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1150"), srcInfo.FullName), Location); } bool destOutdated = !destInfo.Exists || srcInfo.LastWriteTime > destInfo.LastWriteTime || XsltFile.LastWriteTime > destInfo.LastWriteTime; if (destOutdated) { XmlReader xmlReader = null; XmlReader xslReader = null; TextWriter writer = null; try { // store current directory string originalCurrentDirectory = Directory.GetCurrentDirectory(); // initialize XPath document holding input XML XPathDocument xml = null; try { // change current directory to directory containing // XSLT file, to allow includes to be resolved // correctly Directory.SetCurrentDirectory(srcInfo.DirectoryName); // load the xml that needs to be transformed Log(Level.Verbose, "Loading XML file '{0}'.", srcInfo.FullName); xmlReader = CreateXmlReader(srcInfo.FullName); xml = new XPathDocument(xmlReader); } finally { // restore original current directory Directory.SetCurrentDirectory(originalCurrentDirectory); } // initialize xslt parameters XsltArgumentList xsltArgs = new XsltArgumentList(); // set the xslt parameters foreach (XsltParameter parameter in Parameters) { if (IfDefined && !UnlessDefined) { xsltArgs.AddParam(parameter.ParameterName, parameter.NamespaceUri, parameter.Value); } } // create extension objects foreach (XsltExtensionObject extensionObject in ExtensionObjects) { if (extensionObject.IfDefined && !extensionObject.UnlessDefined) { object extensionInstance = extensionObject.CreateInstance(); xsltArgs.AddExtensionObject(extensionObject.NamespaceUri, extensionInstance); } } // initialize XSLT transform XslTransform xslt = new XslTransform(); try { // change current directory to directory containing // XSLT file, to allow includes to be resolved // correctly Directory.SetCurrentDirectory(XsltFile.DirectoryName); // load the stylesheet Log(Level.Verbose, "Loading stylesheet '{0}'.", XsltFile.FullName); xslReader = CreateXmlReader(XsltFile.FullName); xslt.Load(xslReader); // create writer for the destination xml writer = CreateWriter(destInfo.FullName); // do the actual transformation Log(Level.Info, "Processing '{0}' to '{1}'.", srcInfo.FullName, destInfo.FullName); xslt.Transform(xml, xsltArgs, writer); } finally { // restore original current directory Directory.SetCurrentDirectory(originalCurrentDirectory); } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1151"), srcInfo.FullName, XsltFile.FullName), Location, ex); } finally { // ensure file handles are closed if (xmlReader != null) { xmlReader.Close(); } if (xslReader != null) { xslReader.Close(); } if (writer != null) { writer.Close(); } } } } }
private void MakeTransform(XslTransform transform, string fileName) { transform.Load(Path.Combine(Path.Combine(_resourceDirectory, "xslt"), fileName)); }
public XsltTransformer() { xslTransform = new XslTransform(); }
public static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: svg2xaml input.svg [output.xaml].\n"); Console.WriteLine(" If you don't specify an output file, it will be created"); Console.WriteLine(" as 'input.svg.xaml' in the location of the svg file."); return; } string input = args[0]; if (!File.Exists(input)) { Console.WriteLine("Error: file {0} does not exist."); Console.WriteLine("This might work better if you try and convert an svg that actually exists."); return; } string output = input + ".xaml"; if (args.Length > 1) { output = args[1]; } Console.WriteLine("Converting file {0} into {1}...", input, output); XmlDocument xsltdoc = new XmlDocument(); try { Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("svg2xaml.xslt"); xsltdoc.Load(s); } catch (FileNotFoundException e) { Console.WriteLine("Ooops, can't find the transformation stylesheet. That won't work :p"); return; } catch (Exception ex) { Console.WriteLine(ex.Message); return; } try { XslTransform t = new XslTransform(); t.Load(xsltdoc); t.Transform(input, output); } catch (Exception ex) { Console.WriteLine("Houston, we have a problem!"); Exception a = ex; Console.WriteLine(a.Message); Console.WriteLine(a.StackTrace); while (a != null) { Console.WriteLine(a.Message); a = ex.InnerException; } } Console.WriteLine("Conversion done, file {0} created. Have a nice day :)", output); }
/// <summary> /// Transforms the <see cref="XmlDocument"/>. /// </summary> /// <param name="document">The document to be transformed.</param> /// <returns>Returns the resulting <see cref="XmlDocument"/>.</returns> public XmlDocument Transform(XmlDocument document) { XslTransform xslt = new XslTransform(); XsltArgumentList args = new XsltArgumentList(); if (HttpContext.Current == null) { xslt.Load(System.IO.Path.Combine(basePath,this.Type) + ".xslt"); } else { xslt.Load(HttpContext.Current.Server.MapPath(this.Type + ".xslt")); foreach (string key in HttpContext.Current.Request.Params.AllKeys) { try { args.AddParam(key, String.Empty, HttpContext.Current.Request.Params[key]); } catch (Exception ex) { } } } MemoryStream ms = new MemoryStream(); xslt.Transform(document, args, ms); XmlDocument output = new XmlDocument(); output.LoadXml(System.Text.Encoding.ASCII.GetString(ms.ToArray())); return output; }
public static XslTransform GetXslTransform(XslTransform xform) { return(AppSettings.RestrictXmlControls ? null : xform); }
private static XslTransform LoadTransform(string name) { try { XmlDocument xsl = new XmlDocument(); xsl.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream(name)); if (name == "overview.xsl") { // bit of a hack. overview needs the templates in stylesheet // for doc formatting, and rather than write a resolver, I'll // just do the import for it. XmlNode importnode = xsl.DocumentElement.SelectSingleNode("*[name()='xsl:include']"); xsl.DocumentElement.RemoveChild(importnode); XmlDocument xsl2 = new XmlDocument(); xsl2.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream("stylesheet.xsl")); foreach (XmlNode node in xsl2.DocumentElement.ChildNodes) xsl.DocumentElement.AppendChild(xsl.ImportNode(node, true)); } XslTransform t = new XslTransform(); t.Load (xsl, new ManifestResourceResolver (opts.source)); return t; } catch (Exception e) { throw new ApplicationException("Error loading " + name + " from internal resource", e); } }
private void genExcelByXSL() { DataTable dt = getData(); XmlDataDocument xdd = new XmlDataDocument(dt.DataSet); Response.ContentType = "application/vnd.ms-excel"; Response.Charset = ""; XslTransform xt = new XslTransform(); xt.Load(Server.MapPath("xml/excelTemp.xslt")); xt.Transform(xdd, null, Response.OutputStream); Response.End(); }
public void LoadCruiseControl() { XslTransform transform = ResourceHelper.ReportCruiseControlTransform; }
public static void Main(string[] args) { if (args.Length != 2) return; // Read in the output rules files XmlDocument stylesheet = new XmlDocument(); XmlElement stylesheet_root = stylesheet.CreateElement("xsl:stylesheet", "http://www.w3.org/1999/XSL/Transform"); stylesheet_root.SetAttribute("version", "1.0"); stylesheet.AppendChild(stylesheet_root); /*XmlElement outputnode = stylesheet.CreateElement("xsl:output", "http://www.w3.org/1999/XSL/Transform"); outputnode.SetAttribute("method", "text"); stylesheet_root.AppendChild(outputnode);*/ XmlElement basetemplate = stylesheet.CreateElement("xsl:template", "http://www.w3.org/1999/XSL/Transform"); basetemplate.SetAttribute("match", "*"); basetemplate.InnerXml = "[<xsl:value-of xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select=\"name()\"/>:" + "<xsl:for-each select='*' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" + "[<xsl:value-of select='name(.)'/>]" + "</xsl:for-each>]"; stylesheet_root.AppendChild(basetemplate); StreamReader csgen = new StreamReader("csgen.txt"); System.Text.RegularExpressions.Regex SubstParam = new System.Text.RegularExpressions.Regex(@"@([\w\*]+)(\[[^\]]+\])?"); string csgen_line; while ((csgen_line = csgen.ReadLine()) != null) { if (csgen_line == "" || csgen_line[0] == '#') { continue; } int sp = csgen_line.IndexOf(" "); if (sp == -1) { continue; } string rule = csgen_line.Substring(sp+1); int priority = -1; if (csgen_line.StartsWith("*")) priority = 10; if (csgen_line.StartsWith("!")) { priority = 20; csgen_line = csgen_line.Substring(1); } XmlElement template = stylesheet.CreateElement("xsl:template", "http://www.w3.org/1999/XSL/Transform"); template.SetAttribute("match", csgen_line.Substring(0, sp)); template.SetAttribute("xml:space", "preserve"); if (priority != -1) template.SetAttribute("priority", priority.ToString()); if (rule == "none") { template.InnerXml = "<xsl:apply-templates xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select='*'/>"; } else if (rule == "text") { template.InnerXml = "<xsl:value-of xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select='@Text'/>"; } else { rule = rule.Replace("|", "\n"); if (!rule.EndsWith("\\")) rule += "\n"; else rule = rule.Substring(0, rule.Length-1); rule = rule.Replace("@@1", "<xsl:apply-templates xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select='*[position()>1]'/>"); rule = rule.Replace("@@", "<xsl:apply-templates xmlns:xsl='http://www.w3.org/1999/XSL/Transform'/>"); foreach (System.Text.RegularExpressions.Match match in SubstParam.Matches(rule)) { string type = match.Result("$1"); string sep = match.Result("$2"); if (sep != "") sep = sep.Substring(1, sep.Length-2); if (type == "text") { rule = rule.Replace(match.Value, "<xsl:value-of xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select='@Text'/>"); } else { if (char.IsDigit(type[0])) type = "*[position()=" + type + "]"; if (sep == "") rule = rule.Replace(match.Value, "<xsl:apply-templates xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select='" + type + "'/>"); else rule = rule.Replace(match.Value, "<xsl:for-each xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select='" + type + "'>" + "<xsl:if test='not(position()=1)'>" + sep + "</xsl:if>" + "<xsl:apply-templates select='.'/>" + "</xsl:for-each>"); } } template.InnerXml = rule; } stylesheet_root.AppendChild(template); } CSharpAST left = GetAST(args[0]), right = GetAST(args[1]); StringWriter buffer = new StringWriter(); XmlTextWriter output = new XmlTextWriter(buffer); //output.Formatting = Formatting.Indented; StructuredDiff test = new XmlOutputStructuredDiff(output, null); test.AddInterface(typeof(ASTNode), new ASTNodeInterface()); test.Compare(left, right); output.Close(); XmlDocument diff = new XmlDocument(); diff.LoadXml(buffer.ToString()); XslTransform transform = new XslTransform(); transform.Load(stylesheet); XmlReader diffcontent = transform.Transform(diff, null); throw new Exception(diffcontent.BaseURI == null ? "null" : "not null"); XmlDocument diffdoc = new XmlDocument(); diffdoc.Load(diffcontent); diffdoc.Normalize(); WriteChildren(diffdoc.DocumentElement, 0, ' '); Console.WriteLine(); }
public static void CheckDiff (string diffFile) { int suc=0, tot=0, ign=0; XmlDocument doc = new XmlDocument (); doc.Load (diffFile); XmlDocument errdoc = new XmlDocument (); errdoc.Load ("proxy-gen-error.xml"); XmlDocument result = new XmlDocument (); XmlElement res = result.CreateElement ("test-results"); res.SetAttribute ("name", "wsdl-tests"); res.SetAttribute ("date", DateTime.Now.ToShortDateString ()); res.SetAttribute ("time", DateTime.Now.ToShortTimeString ()); result.AppendChild (res); XmlElement ts = result.CreateElement ("test-suite"); ts.SetAttribute ("name", "wsdl"); ts.SetAttribute ("asserts", "0"); ts.SetAttribute ("time", "0"); res.AppendChild (ts); XmlElement tsres = result.CreateElement ("results"); ts.AppendChild (tsres); XslTransform xsl = new XslTransform (); xsl.Load ("cormissing.xsl"); foreach (ServiceData sd in services.services) { if (sd.Protocols == null) continue; foreach (string prot in sd.Protocols) { string ns = sd.Namespace + "." + prot; XmlElement elem = doc.SelectSingleNode ("assemblies/assembly/namespaces/namespace[@name='" + ns + "']") as XmlElement; if (elem == null) { ign++; continue; } if (!File.Exists (GetWsdlFile(sd))) { Console.WriteLine ("WARNING: wsdl file not found: " + GetWsdlFile(sd)); ign++; continue; } tot++; bool extrans = elem.GetAttribute ("presence") == "extra"; if ((elem.GetAttribute ("error") != "" || elem.GetAttribute ("missing") != "" || elem.GetAttribute ("extra") != "") && !extrans) { XmlElement errelem = errdoc.SelectSingleNode ("/errors/error[@ns='" + ns + "']") as XmlElement; if (errelem != null) { WriteResult (tsres, ns, false, sd.Wsdl + "\n" + errelem.InnerText); } else { StringWriter str = new StringWriter (); xsl.Transform (elem, null, str, null); WriteResult (tsres, ns, false, sd.Wsdl + "\n" + str.ToString ()); } } else { if (extrans) Console.WriteLine ("BONUS CLASS: " + ns); suc++; WriteResult (tsres, ns, true, sd.Wsdl); } } } ts.SetAttribute ("success", (suc < tot).ToString()); res.SetAttribute ("total", tot.ToString()); res.SetAttribute ("failures", (tot-suc).ToString()); res.SetAttribute ("not-run", "0"); result.Save ("WsdlTestResult.xml"); Console.WriteLine ("Compared:" + tot + " Ignored:" + ign + " Sucess:" + suc + " Fail:" + (tot - suc)); }
private void CreateSummaryDocument() { XPathDocument originalXPathDocument = new XPathDocument (new FileStream (outputFile, FileMode.Open)); XslTransform summaryXslTransform = new XslTransform(); summaryXslTransform.Load(transformReader); summaryXslTransform.Transform(originalXPathDocument,null,Console.Out); }
private static void ProcesoDir(KnowledgeBase KB, string directoryArg, string newDir, string generator, IOutputService output) { string outputFile = KB.UserDirectory + @"\KBdoctorEv2.xslt"; XslTransform xslTransform = new XslTransform(); output.AddLine("Cargando archivo xslt: " + outputFile); xslTransform.Load(outputFile); output.AddLine("Archivo xslt cargado correctamente."); string fileWildcard = @"*.xml"; var searchSubDirsArg = System.IO.SearchOption.AllDirectories; string[] xFiles = System.IO.Directory.GetFiles(directoryArg, fileWildcard, searchSubDirsArg); Hashtable colisiones = new Hashtable(); HashSet <string> colisionesStr = new HashSet <string>(); //Busco colisiones en los nombres de los archivos foreach (string x in xFiles) { string filename = Path.GetFileNameWithoutExtension(x); if (!colisiones.Contains(filename)) { List <string> paths = new List <string>(); paths.Add(x); colisiones[filename] = paths; } else { List <string> paths = (List <string>)colisiones[filename]; paths.Add(x); colisiones[filename] = paths; if (!colisionesStr.Contains(filename)) { colisionesStr.Add(filename); } } } //Me quedo sólo con el archivo más nuevo y cambio el nombre de todos los demás. foreach (string name in colisionesStr) { FileInfo newestFile = null; DateTime newestDate = new DateTime(1891, 09, 28); List <string> paths = (List <string>)colisiones[name]; List <FileInfo> oldfiles = new List <FileInfo>(); foreach (string path in paths) { FileInfo file = new FileInfo(path); if (file.LastWriteTime >= newestDate) { if (newestFile != null) { oldfiles.Add(newestFile); } newestDate = file.LastWriteTime; newestFile = file; } else { oldfiles.Add(file); } } int i = 1; foreach (FileInfo fileToRename in oldfiles) { fileToRename.MoveTo(fileToRename.DirectoryName + '\\' + Path.GetFileNameWithoutExtension(fileToRename.Name) + i.ToString() + ".oldxml"); i++; } } xFiles = System.IO.Directory.GetFiles(directoryArg, fileWildcard, searchSubDirsArg); foreach (string x in xFiles) { if (!Path.GetFileNameWithoutExtension(x).StartsWith("Gx0")) { try { string xTxt = newDir + generator + Path.GetFileNameWithoutExtension(x) + ".nvg"; string xmlstring = Utility.AddXMLHeader(x); string newXmlFile = x.Replace(".xml", ".xxx"); File.WriteAllText(newXmlFile, xmlstring); xslTransform.Transform(newXmlFile, xTxt); File.Delete(newXmlFile); } catch (Exception e) { output.AddErrorLine(e); } } } }
// Function : Export_with_XSLT_Web // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName // Purpose : Exports dataset into CSV / Excel format private void Export_with_XSLT_Web(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName) { try { // Appending Headers response.Clear(); response.Buffer= true; response.ContentEncoding = Encoding.GetEncoding("GB2312"); if(FormatType == ExportFormat.CSV) { response.ContentType = "text/csv"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } else { response.ContentType = "application/vnd.ms-excel"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } // XSLT to use for transforming this dataset. MemoryStream stream = new MemoryStream( ); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush( ); stream.Seek( 0, SeekOrigin.Begin); XmlDataDocument xmlDoc = new XmlDataDocument(dsExport); XslTransform xslTran = new XslTransform();//��ʱ���� //XslCompiledTransform xslTran = new XslCompiledTransform(); xslTran.Load(new XmlTextReader(stream), null, null); System.IO.StringWriter sw = new System.IO.StringWriter(); xslTran.Transform(xmlDoc, null, sw, null); //Writeout the Content response.Write(sw.ToString()); sw.Close(); writer.Close(); stream.Close(); response.End(); } catch(ThreadAbortException Ex) { string ErrMsg = Ex.Message; } catch(Exception Ex) { throw Ex; } }
private static void Main2() { if (opts.dumptemplate) { DumpTemplate(); return; } if (opts.source == null || opts.source == "" || opts.dest == null || opts.dest == "") { throw new ApplicationException("The source and dest options must be specified."); } Directory.CreateDirectory(opts.dest); // Load the stylesheets, overview.xml, and resolver XslTransform overviewxsl = LoadTransform("overview.xsl"); XslTransform stylesheet = LoadTransform("stylesheet.xsl"); XslTransform template; if (opts.template == null) { template = LoadTransform("defaulttemplate.xsl"); } else { try { XmlDocument templatexsl = new XmlDocument(); templatexsl.Load(opts.template); template = new XslTransform(); template.Load(templatexsl); } catch (Exception e) { throw new ApplicationException("There was an error loading " + opts.template, e); } } XmlDocument overview = new XmlDocument(); overview.Load(opts.source + "/index.xml"); ArrayList extensions = GetExtensionMethods(overview); // Create the master page XsltArgumentList overviewargs = new XsltArgumentList(); overviewargs.AddParam("ext", "", opts.ext); overviewargs.AddParam("basepath", "", "./"); Generate(overview, overviewxsl, overviewargs, opts.dest + "/index." + opts.ext, template); overviewargs.RemoveParam("basepath", ""); overviewargs.AddParam("basepath", "", "../"); // Create the namespace & type pages XsltArgumentList typeargs = new XsltArgumentList(); typeargs.AddParam("ext", "", opts.ext); typeargs.AddParam("basepath", "", "../"); foreach (XmlElement ns in overview.SelectNodes("Overview/Types/Namespace")) { string nsname = ns.GetAttribute("Name"); if (opts.onlytype != null && !opts.onlytype.StartsWith(nsname + ".")) { continue; } System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(opts.dest + "/" + nsname); if (!d.Exists) { d.Create(); } // Create the NS page overviewargs.AddParam("namespace", "", nsname); Generate(overview, overviewxsl, overviewargs, opts.dest + "/" + nsname + "/index." + opts.ext, template); overviewargs.RemoveParam("namespace", ""); foreach (XmlElement ty in ns.SelectNodes("Type")) { string typefilebase = ty.GetAttribute("Name"); string typename = ty.GetAttribute("DisplayName"); if (typename.Length == 0) { typename = typefilebase; } if (opts.onlytype != null && !(nsname + "." + typename).StartsWith(opts.onlytype)) { continue; } string typefile = opts.source + "/" + nsname + "/" + typefilebase + ".xml"; if (!File.Exists(typefile)) { continue; } XmlDocument typexml = new XmlDocument(); typexml.Load(typefile); if (extensions != null) { DocLoader loader = CreateDocLoader(overview); XmlDocUtils.AddExtensionMethods(typexml, extensions, loader); } Console.WriteLine(nsname + "." + typename); Generate(typexml, stylesheet, typeargs, opts.dest + "/" + nsname + "/" + typefilebase + "." + opts.ext, template); } } }
// Function : Export_with_XSLT_Windows // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName // Purpose : Exports dataset into CSV / Excel format private void Export_with_XSLT_Windows(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName) { try { // XSLT to use for transforming this dataset. MemoryStream stream = new MemoryStream( ); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush( ); stream.Seek( 0, SeekOrigin.Begin); XmlDataDocument xmlDoc = new XmlDataDocument(dsExport); XslTransform xslTran = new XslTransform();//��ʱ���� //XslCompiledTransform xslTran = new XslCompiledTransform(); xslTran.Load(new XmlTextReader(stream), null, null); System.IO.StringWriter sw = new System.IO.StringWriter(); xslTran.Transform(xmlDoc, null, sw, null); //Writeout the Content StreamWriter strwriter = new StreamWriter(FileName); strwriter.WriteLine(sw.ToString()); strwriter.Close(); sw.Close(); writer.Close(); stream.Close(); } catch(Exception Ex) { throw Ex; } }
override void Render(HtmlTextWriter output) { XmlDocument xml_doc = null; if (xpath_navigator == null) { if (xml_document != null) { xml_doc = xml_document; } else { if (xml_content != null) { xml_doc = new XmlDocument(); xml_doc.LoadXml(xml_content); } else if (xml_file != null) { xml_doc = new XmlDocument(); xml_doc.Load(MapPathSecure(xml_file)); } else { return; } } } XslTransform t = xsl_transform; if (transform_file != null) { t = new XslTransform(); t.Load(MapPathSecure(transform_file)); } if (t != null) { if (xpath_navigator != null) { t.Transform(xpath_navigator, transform_arguments, output); } else { t.Transform(xml_doc, transform_arguments, output, null); } return; } XmlTextWriter xmlwriter = new XmlTextWriter(output); xmlwriter.Formatting = Formatting.None; if (xpath_navigator != null) { xmlwriter.WriteStartDocument(); xpath_navigator.WriteSubtree(xmlwriter); } else { xml_doc.Save(xmlwriter); } }
private static void Generate(XmlDocument source, XslTransform transform, XsltArgumentList args, string output, XslTransform template) { using (TextWriter textwriter = new StreamWriter(new FileStream(output, FileMode.Create))) { XmlTextWriter writer = new XmlTextWriter(textwriter); writer.Formatting = Formatting.Indented; writer.Indentation = 2; writer.IndentChar = ' '; try { XmlDocument intermediate = new XmlDocument(); intermediate.PreserveWhitespace = true; intermediate.Load(transform.Transform(source, args, new ManifestResourceResolver(opts.source))); template.Transform(intermediate, new XsltArgumentList(), new XhtmlWriter (writer), null); } catch (Exception e) { throw new ApplicationException("An error occured while generating " + output, e); } } }
private void LoadTransformFromSource() { // We're done if we already have a transform if (_transform != null) { return; } if (String.IsNullOrEmpty(_transformSource) || _transformSource.Trim().Length == 0) { return; } // First, figure out if it's a physical or virtual path VirtualPath virtualPath; string physicalPath; ResolvePhysicalOrVirtualPath(_transformSource, out virtualPath, out physicalPath); CacheStoreProvider cacheInternal = HttpRuntime.Cache.InternalCache; string key = CacheInternal.PrefixLoadXPath + ((physicalPath != null) ? physicalPath : virtualPath.VirtualPathString); object xform = cacheInternal.Get(key); if (xform == null) { Debug.Trace("XmlControl", "Xsl Transform not found in cache (" + _transformSource + ")"); // Get the stream, and open the doc CacheDependency dependency; using (Stream stream = OpenFileAndGetDependency(virtualPath, physicalPath, out dependency)) { // If we don't have a physical path, call MapPath to get one, in order to pass it as // the baseUri to XmlTextReader. In pure VirtualPathProvider scenarios, it won't // help much, but it allows the default case to have relative references (VSWhidbey 545322) if (physicalPath == null) { physicalPath = virtualPath.MapPath(); } // XslCompiledTransform for some reason wants to completely re-create an internal XmlReader // from scratch. In doing so, it does not respect all the settings of XmlTextReader. So we want // to be sure to specifically use XmlReader here so our settings on it will be respected by the // XslCompiledTransform. XmlReader xmlReader = XmlUtils.CreateXmlReader(stream, physicalPath); _transform = XmlUtils.CreateXslTransform(xmlReader); if (_transform == null) { _compiledTransform = XmlUtils.CreateXslCompiledTransform(xmlReader); } } // Cache it, but only if we got a dependency if (dependency != null) { using (dependency) { cacheInternal.Insert(key, ((_compiledTransform == null) ? (object)_transform : (object)_compiledTransform), new CacheInsertOptions() { Dependencies = dependency }); } } } else { Debug.Trace("XmlControl", "XslTransform found in cache (" + _transformSource + ")"); _compiledTransform = xform as XslCompiledTransform; if (_compiledTransform == null) { #pragma warning disable 0618 // To avoid deprecation warning _transform = (XslTransform)xform; #pragma warning restore 0618 } } }
private static void Main2() { if (opts.dumptemplate) { DumpTemplate(); return; } if (opts.source == null || opts.source == "" || opts.dest == null || opts.dest == "") throw new ApplicationException("The source and dest options must be specified."); Directory.CreateDirectory(opts.dest); // Load the stylesheets, overview.xml, and resolver XslTransform overviewxsl = LoadTransform("overview.xsl"); XslTransform stylesheet = LoadTransform("stylesheet.xsl"); XslTransform template; if (opts.template == null) { template = LoadTransform("defaulttemplate.xsl"); } else { try { XmlDocument templatexsl = new XmlDocument(); templatexsl.Load(opts.template); template = new XslTransform(); template.Load(templatexsl); } catch (Exception e) { throw new ApplicationException("There was an error loading " + opts.template, e); } } XmlDocument overview = new XmlDocument(); overview.Load(opts.source + "/index.xml"); ArrayList extensions = GetExtensionMethods (overview); // Create the master page XsltArgumentList overviewargs = new XsltArgumentList(); overviewargs.AddParam("ext", "", opts.ext); overviewargs.AddParam("basepath", "", "./"); Generate(overview, overviewxsl, overviewargs, opts.dest + "/index." + opts.ext, template); overviewargs.RemoveParam("basepath", ""); overviewargs.AddParam("basepath", "", "../"); // Create the namespace & type pages XsltArgumentList typeargs = new XsltArgumentList(); typeargs.AddParam("ext", "", opts.ext); typeargs.AddParam("basepath", "", "../"); foreach (XmlElement ns in overview.SelectNodes("Overview/Types/Namespace")) { string nsname = ns.GetAttribute("Name"); if (opts.onlytype != null && !opts.onlytype.StartsWith(nsname + ".")) continue; System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(opts.dest + "/" + nsname); if (!d.Exists) d.Create(); // Create the NS page overviewargs.AddParam("namespace", "", nsname); Generate(overview, overviewxsl, overviewargs, opts.dest + "/" + nsname + "/index." + opts.ext, template); overviewargs.RemoveParam("namespace", ""); foreach (XmlElement ty in ns.SelectNodes("Type")) { string typefilebase = ty.GetAttribute("Name"); string typename = ty.GetAttribute("DisplayName"); if (typename.Length == 0) typename = typefilebase; if (opts.onlytype != null && !(nsname + "." + typename).StartsWith(opts.onlytype)) continue; string typefile = opts.source + "/" + nsname + "/" + typefilebase + ".xml"; if (!File.Exists(typefile)) continue; XmlDocument typexml = new XmlDocument(); typexml.Load(typefile); if (extensions != null) { DocLoader loader = CreateDocLoader (overview); XmlDocUtils.AddExtensionMethods (typexml, extensions, loader); } Console.WriteLine(nsname + "." + typename); Generate(typexml, stylesheet, typeargs, opts.dest + "/" + nsname + "/" + typefilebase + "." + opts.ext, template); } } }
public void LoadHtml() { XslTransform transform = ResourceHelper.ReportHtmlTransform; }