public void InvalidStylesheet () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<xsl:element xmlns:xsl='http://www.w3.org/1999/XSL/Transform' />"); XslTransform t = new XslTransform (); t.Load (doc); }
public static bool TransformDirectory(string source) { string stylesheet = "mn2db.xsl"; string destination = "docbook" + Path.DirectorySeparatorChar; // create destination directory if needed string destdir = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + destination; try { if(!Directory.Exists(destdir)) { Directory.CreateDirectory(destdir); } // transform the documents in the directory string[] filelist = Directory.GetFiles(source,"*.xml"); XslTransform transform = new XslTransform(); transform.Load(stylesheet); foreach(string sourcefile in filelist) { string destfile = destdir + Path.GetFileName(sourcefile); Console.WriteLine("Transforming {0}",sourcefile); transform.Transform(sourcefile, destfile); } } catch(Exception e) { throw new Mn2DbTransformException(e.ToString()); } return true; }
public static string Transform(string xml,string xslFile) { XslTransform transform = new XslTransform(); XsltArgumentList args = new XsltArgumentList(); //define the xslt rendering file //get the iterators for the root and context item XPathDocument xmlDoc = new XPathDocument(new StringReader(xml)); XPathNavigator iter = xmlDoc.CreateNavigator(); //define and add the xslt extension classes //Sitecore.Xml.Xsl.XslHelper sc = new Sitecore.Xml.Xsl.XslHelper(); XsltHelper xslt = new XsltHelper(); args.AddExtensionObject("http://www.rlmcore.vn/helper", xslt); //add parameters args.AddParam("item", "", iter); args.AddParam("currentitem", "", iter.Select(".")); //define the stream which will contain the result of xslt transformation //StringBuilder sb = new StringBuilder(); //TextWriter stream = new FileStream(new MemoryStream(Encoding.ASCII.GetBytes(sb.ToString()))); System.IO.StringWriter stream = new System.IO.StringWriter(); //load xslt rendering to XslTransform class transform.Load(xslFile); //perform a transformation with the rendering transform.Transform(iter, args, stream); return stream.ToString(); }
public void TransformingTest() { XslTransform tx = new XslTransform(); tx.Load(new XmlTextReader( Globals.GetResource(this.GetType().Namespace + ".test.xsl"))); XmlReader xtr = new XmlTransformingReader( new XmlTextReader( Globals.GetResource(this.GetType().Namespace + ".input.xml")), tx); //That's it, now let's dump out XmlTransformingReader to see what it returns StringWriter sw = new StringWriter(); XmlTextWriter w = new XmlTextWriter(sw); w.Formatting = Formatting.Indented; w.WriteNode(xtr, false); xtr.Close(); w.Close(); Assert.AreEqual(sw.ToString(), @"<parts> <item SKU=""1001"" name=""Lawnmower"" price=""299.99"" /> <item SKU=""1001"" name=""Electric drill"" price=""99.99"" /> <item SKU=""1001"" name=""Hairdrier"" price=""39.99"" /> </parts>"); }
private void BindAuto(Rubric rub) { Result.ResultList ress = new Rubrics(Globals.CurrentIdentity).GetResults(rub.ID, GetCurrentSub()); if (ress.Count == 0) { divAuto.InnerHtml = "<i>There are no results for this evaluation item</i>"; return; } AutoResult res = ress[0] as AutoResult; MemoryStream xmlstr = new MemoryStream(Encoding.ASCII.GetBytes(res.XmlResult)); XslTransform xslt = new XslTransform(); XPathDocument xpathdoc = new XPathDocument(xmlstr); XPathNavigator nav = xpathdoc.CreateNavigator(); XPathDocument xsldoc = new XPathDocument( Path.Combine(Globals.WWWDirectory, "Xml/reshtml.xslt")); StringBuilder strb = new StringBuilder(); xslt.Load(xsldoc, null, null); xslt.Transform(xpathdoc, null, new XmlTextWriter(new StringWriter(strb)) , (XmlResolver)null); divAuto.InnerHtml = strb.ToString(); }
protected virtual string GetDataSummary(Stream xsltStream) { DataSet data = this.GetDataSet; if (xsltStream == null || data == null) return null; Stream dsStream = new MemoryStream(); data.WriteXml(dsStream); TextWriter tw = new StringWriter(); try { XslTransform xsl = new XslTransform(); XmlDocument XSLTDoc = new XmlDocument(); XSLTDoc.Load(xsltStream); XmlDocument dataDoc = new XmlDocument(); dataDoc.LoadXml(data.GetXml()); XPathNavigator stylesheet = XSLTDoc.CreateNavigator(); xsl.Load(stylesheet, null, null); XPathNavigator dataNav = dataDoc.CreateNavigator(); xsl.Transform(dataNav, null, tw, null); } catch (Exception ex) { return null; } return tw.ToString(); }
/// <summary> /// This function retuns list of states for a given country as XML Document in a string /// and this value is used in client side java script to populate state combo box. /// Functionality: Transform the CountriesAndStates xml string into another XML string having the single country /// and states under that country. /// </summary> public string GetStatesXMLString(string countryName) { //Creates a XslTransform object and load the CountriesAndStates.xsl file XslTransform transformToCountryNode = new XslTransform(); transformToCountryNode.Load(new XPathDocument(HttpContext.Current.Server.MapPath("~/xmlxsl/CountriesAndStates.xsl")).CreateNavigator(), new XmlUrlResolver()); //TransformToCountryNode.Load(new XPathDocument(HttpContext.Current.Server.MapPath("~/xmlxsl/CountriesAndStates.xsl")).CreateNavigator(), new XmlUrlResolver(), this.GetType().Assembly.Evidence); //Creating the XSLT parameter country-name and setting the value XsltArgumentList xslArgs = new XsltArgumentList(); xslArgs.AddParam("country-name", "", countryName); // Memory stream to store the result of XSL transform MemoryStream countryNodeMemoryStream = new MemoryStream(); XmlTextWriter countryNodeXmlTextWriter = new XmlTextWriter(countryNodeMemoryStream, Encoding.UTF8); countryNodeXmlTextWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); //transforming the current XML string to get the state XML string transformToCountryNode.Transform(xPathDoc, xslArgs, countryNodeXmlTextWriter); //TransformToCountryNode.Transform(XPathDoc, XslArgs, CountryNodeXmlTextWriter, null); //reading the XML string using StreamReader and return the same countryNodeXmlTextWriter.Flush(); countryNodeMemoryStream.Position = 0; StreamReader countryNodeStreamReader = new StreamReader(countryNodeMemoryStream); return countryNodeStreamReader.ReadToEnd(); }
static Xml () { XmlTextReader reader = new XmlTextReader (new StringReader("<xsl:stylesheet version='1.0' " + "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" + "<xsl:template match=\"*\">" + "<xsl:copy-of select=\".\"/>" + "</xsl:template>" + "</xsl:stylesheet>")); defaultTransform = new XslTransform(); #if NET_1_0 defaultTransform.Load (reader); #else defaultTransform.Load (reader, null, null); #endif }
public void RunXslt(String xsltFile, String xmlDataFile, String outputXml) { XPathDocument input = new XPathDocument(xmlDataFile); XslTransform myXslTrans = new XslTransform() ; XmlTextWriter output = null; try { myXslTrans.Load(xsltFile); output = new XmlTextWriter(outputXml, null); output.Formatting = Formatting.Indented; myXslTrans.Transform(input, null, output); } catch (Exception e) { String msg = e.Message; if (msg.IndexOf("InnerException") >0) { msg = e.InnerException.Message; } MessageBox.Show("Error: " + msg + "\n" + e.StackTrace, "Xslt Error File: " + xsltFile, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { try { output.Close(); } catch (Exception) { } } }
public static void Parse( XmlDocument xmlMetadata_in, string xsltTemplateURL_in, Hashtable xsltParameters_in, StringWriter parsedOutput_in ) { #region XsltArgumentList _xsltparameters = new XsltArgumentList().AddParam(...); XsltArgumentList _xsltparameters = new XsltArgumentList(); IDictionaryEnumerator _denum = xsltParameters_in.GetEnumerator(); _denum.Reset(); while (_denum.MoveNext()) { _xsltparameters.AddParam( _denum.Key.ToString(), "", System.Web.HttpUtility.UrlEncode( _denum.Value.ToString() ) ); } #endregion XPathNavigator _xpathnav = xmlMetadata_in.CreateNavigator(); XslTransform _xslttransform = new XslTransform(); _xslttransform.Load( xsltTemplateURL_in ); _xslttransform.Transform( _xpathnav, _xsltparameters, parsedOutput_in, null ); }
/* KCS: 2012/03/19 - Changed to be able to pass args to the template. * * xslt <xsltFile> <inputXml> <outputFile> <parm1Name> = <parm1Value> <parm2Name> = <parm2Value> ..... */ public void RunXSLT(String xsltFile, String xmlDataFile, String outFile, XsltArgumentList xsltArgs ) { XPathDocument input = new XPathDocument(xmlDataFile); XslTransform myXslTrans = new XslTransform(); XmlTextWriter output = null; try { myXslTrans.Load(xsltFile); output = new XmlTextWriter(outFile, null); output.Formatting = Formatting.Indented; myXslTrans.Transform(input, xsltArgs, output); } catch (Exception e) { Console.WriteLine(e.StackTrace); Console.WriteLine("Error: " + e.Message); } finally { try { output.Close(); } catch (Exception) { } } }
static void Main(string[] args) { XslTransform xslt = new XslTransform(); xslt.Load(@"..\Transforms\PAWSSKHtmlMapper.xsl"); string[] astrFiles; astrFiles = Directory.GetFiles(".", "*.xml"); if (astrFiles.Length > 0) { foreach (string strFile in astrFiles) { try { string strDestFile = Path.Combine(@"..\HTMs", Path.GetFileNameWithoutExtension(strFile)); strDestFile += ".htm"; Console.WriteLine("Making {0} from {1}", strDestFile, strFile); xslt.Transform(strFile, strDestFile); } catch (Exception exc) { Console.WriteLine("Error: " + exc); return; } } } }
public void MatchRoot() { XmlDocument xsltDoc = new XmlDocument(); xsltDoc.LoadXml( @" <xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:output method='xml' omit-xml-declaration='no' encoding='UTF-8'/> <xsl:template match='/'><root>Matched</root></xsl:template> </xsl:stylesheet> " ); XslTransform xslt = new XslTransform(); xslt.Load( xsltDoc ); StringBuilder builder = new StringBuilder(); XmlWriter writer = new XmlTextWriter( new StringWriter( builder ) ); CollectionOfSimple c = new CollectionOfSimple( true ); ObjectXPathContext context = new ObjectXPathContext(); context.DetectLoops = true; XPathNavigator nav = context.CreateNavigator( c ); xslt.Transform( nav, null, writer, null ); writer.Close(); Assert.AreEqual( "<root>Matched</root>", builder.ToString() ); }
public ViewGui() { Stetic.Gui.Build(this, typeof(Sofia.Views.WelcomeView.ViewGui)); //Ajout d'une page d'accueil avec un navigateur web htmlControl = new MozillaControl(); this.Add(htmlControl); htmlControl.Show(); string datadir = Directory.GetCurrentDirectory() + "/"; // build simple xml which XSLT will process into XHTML string myxml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + "<WelcomePage>" + "<ResourcePath>" + datadir + "</ResourcePath>" + BuildRecentFoldersXml() + "</WelcomePage>"; XmlDocument inxml = new XmlDocument(); inxml.LoadXml(myxml); XslTransform xslt = new XslTransform(); xslt.Load(datadir + "WelcomePage.xsl"); StringWriter fs = new StringWriter(); xslt.Transform(inxml, null, fs, null); htmlControl.Html = fs.ToString(); }
public Toc2Html () { transform = new XslTransform (); var assembly = Assembly.GetCallingAssembly (); var stream = assembly.GetManifestResourceStream ("toc-html.xsl"); XmlReader xml_reader = new XmlTextReader (stream); transform.Load (xml_reader, null, null); }
/// <summary> /// Creates XmlTransformingReader with given XmlReader, stylesheet URI, /// XsltArgumentList and Xmlresolver. /// </summary> /// <param name="parentReader">Source XML as XmlReader</param> /// <param name="transformSource">URI of the stylesheet to transform the source</param> /// <param name="args">Arguments to the transformation</param> /// <param name="resolver">XmlResolver to resolve URIs in document() function</param> public XmlTransformingReader(XmlReader parentReader, string transformSource, XsltArgumentList args, XmlResolver resolver) { XPathDocument doc = new XPathDocument(parentReader); XslTransform xslt = new XslTransform(); xslt.Load(transformSource); _outReader = xslt.Transform(doc, args, resolver); }
static void Main(string[] args) { XPathDocument myXPathDoc = new XPathDocument("..\\..\\..\\..\\SchoolJournal\\SchoolJournal\\Displaying\\entry.xml"); XslTransform myXslTrans = new XslTransform(); myXslTrans.Load("..\\..\\..\\..\\SchoolJournal\\SchoolJournal\\Displaying\\style1.xsl"); XmlTextWriter myWriter = new XmlTextWriter("..\\..\\result.html", null); myXslTrans.Transform(myXPathDoc, null, myWriter); }
public string generateHtml(string xmlpath) { string xslpath = ranker.lib.libConfig.GetConfigPath() + Path.DirectorySeparatorChar + "result.xsl"; XslTransform xslt = new XslTransform(); xslt.Load(xslpath); string htmlpath = ranker.lib.libConfig.GetConfigPath() + Path.DirectorySeparatorChar +"temp.html"; xslt.Transform(xmlpath,htmlpath ); return htmlpath; }
internal static void Main() { /* this is deprecated, but only for homework purposes */ XslTransform sheetTransrormer = new XslTransform(); sheetTransrormer.Load("../../../styleXSLT.xslt"); sheetTransrormer.Transform("../../../catalogue.xml", "../../transformedCatalogue.html"); Console.WriteLine("Result is in folder solution."); /*I leave on you to find difference with last task...*/ }
public string MakeBegripTxt(XElement begripDoc) { XslTransform tr = new XslTransform(); tr.Load(Path.Combine(NSBundle.MainBundle.ResourcePath,"Xml2iPhone.xslt")); var txt = new StringWriter(); tr.Transform(begripDoc.CreateNavigator(), null, txt); return txt.ToString(); }
static void Main(string[] args) { XPathDocument xPathDoc = new XPathDocument("../../../Tasks1-Task6AndTask8/catalogue.xml"); XslTransform xslTransformer = new XslTransform(); xslTransformer.Load("../../Catalogue.xslt"); XmlTextWriter writer = new XmlTextWriter("../../catalogue.html", Encoding.UTF8); xslTransformer.Transform(xPathDoc, null, writer); }
public void Load(IXPathNavigable stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) { // if (!settings.EnableDocumentFunction) // throw new NotSupportedException ("'document' function cannot be disabled on this framework because it just runs XslTransform which does not support XsltSettings"); if (settings.EnableScript) { throw new NotSupportedException("'msxsl:script' element is not supported on this framework because it does not support run-time code generation"); } impl.Load(stylesheet, stylesheetResolver); }
public static string TransformXMLStream(string xmlStream,string xslPath) { XmlDocument xmlDoc = new XmlDocument(); XslTransform xslDoc = new XslTransform(); xmlDoc.LoadXml(xmlStream); xslDoc.Load(xslPath); StringWriter sw = new StringWriter(); xslDoc.Transform(xmlDoc,null,sw); return sw.GetStringBuilder().ToString(); }
public static string TransformFromMemory(XmlDocument xml, string xstlModel) { XslTransform xslt = new XslTransform(); xslt.Load(xstlModel); StringWriter sr = new StringWriter(); xslt.Transform(xml, null, sr); return sr.ToString(); }
public void Translate( string destinationFile ) { XslTransform transform = new XslTransform(); transform.Load( new XmlTextReader( Assembly.GetExecutingAssembly().GetManifestResourceStream( "NDoc.UsersGuideStager.xslt.htmlcontents.xslt" ) ), null, null ); XmlDocument doc = new XmlDocument(); doc.Load( TransformHtmlToXml() ); transform.Transform( doc, null, File.CreateText( destinationFile ), null ); }
public static void Main(string [] rgstrArgs) { XmlDocument xml = new XmlDocument (); xml.Load (rgstrArgs [0]); XslTransform xsl = new XslTransform (); xsl.Load (rgstrArgs [1]); xsl.Transform (xml, null, Console.Out); }
static public string Transform (string xmldata, string xsluri) { // FIXME: PONER TRY/CATCH PARA EVITAR MOSTRAR EXPLOSIONES DEL TRANSFORM // // CARGA LA HOJA DE ESTILOS System.Xml.Xsl.XslTransform xslt = new System.Xml.Xsl.XslTransform (); try { xslt.Load (System.AppDomain.CurrentDomain.BaseDirectory + "/Public/xml/" + xsluri); } catch (System.IO.FileNotFoundException) { System.Console.WriteLine ("No se ha encontrado el fichero {0}", xsluri); return "Template no encontrado"; } // LEER ENTRADA System.Xml.XmlReader xrd; try { xrd = new XmlTextReader (new System.IO.StringReader (xmldata)); } catch (System.ArgumentNullException) { return "[Contenido vacio (1)]"; } // EJECUTAMOS Y PASAMOS A STRING XPathDocument xpd; try { xpd = new XPathDocument (xrd); } catch (System.Xml.XmlException ex) { return "[xml fuente incorrecto, error: " + ex.Message + "]"; } XmlResolver xrs = new XmlSecureResolver (new XmlUrlResolver (), new PermissionSet (PermissionState.Unrestricted)); XmlReader xr = xslt.Transform (xpd, null, xrs); xrd.Close (); // Output results to string XmlDocument xd = new XmlDocument (); xd.Load (xr); System.IO.StringWriter sw = new System.IO.StringWriter (); try { xd.Save (sw); } catch (System.InvalidOperationException ex) { return "[resultado incorrecto: "+ ex.Message +"]"; } return sw.ToString (); }
private string TransformElements (string source) { XPathDocument doc = new XPathDocument ( new StringReader ("<root>" + source + "</root>")); XslTransform tr = new XslTransform (); tr.Load ("wiki2ecmahelper.xsl"); XmlReader reader = tr.Transform (doc, null, (XmlResolver) null); reader.Read (); // should consume <root> start tag return reader.ReadInnerXml (); }
public static string Transform(string model, string xstlModel) { XslTransform xslt = new XslTransform(); xslt.Load(xstlModel); XPathDocument xpathdocument = new XPathDocument(model); StringWriter sr = new StringWriter(); xslt.Transform(xpathdocument, null, sr); return sr.ToString(); }
public static void Main() { XPathDocument myXPathDoc = new XPathDocument("Catalogue.xml"); XslTransform myXslTrans = new XslTransform(); myXslTrans.Load("stylesheet.xslt"); XmlTextWriter myWriter = new XmlTextWriter("result.html", Encoding.Unicode); myXslTrans.Transform(myXPathDoc, null, myWriter); }
private XslTransform GetXSLT() { if (xslt == null) { if (LogDispatcher != null) LogDispatcher.DispatchLog("XSLTRulesFileDriver loading "+xslFileURI, LogEventImpl.INFO); xslt = new XslTransform(); xslt.Load(xslFileURI); } return xslt; }
public string Transform() { CheckInput(); if (hasError()) { return(getError()); } // load XML XmlDocument docXml = new XmlDocument(); try { docXml.Load(xmlUri); } catch (Exception e) { string[] args = { xmlUri, e.Message }; setError("MM_INVALID_XML_ERROR", args); return(getError()); } // load XSL System.Xml.Xsl.XslTransform xslt = new System.Xml.Xsl.XslTransform(); try { xslt.Load(xslUri); } catch (Exception e) { string[] args = { xslUri, e.Message }; setError("MM_INVALID_XSL_ERROR", args); return(getError()); } XsltArgumentList xslArg = new XsltArgumentList(); foreach (DictionaryEntry entry in parameters) { object val = entry.Value; string key = (string)entry.Key; xslArg.AddParam(key, "", val); } // DO the transformation StringWriter sw = new StringWriter(); try { xslt.Transform(docXml, xslArg, sw, null); } catch (Exception e) { string[] args = { e.Message }; setError("MM_TRANSFORM_ERROR", args); return(getError()); } return(sw.ToString()); }
public static Stream XslTransform(string resource, Stream input, params DictionaryEntry[] entries) { int tickCount = Environment.TickCount; Stream embeddedResourceStream = Util.GetEmbeddedResourceStream(resource); int num2 = Environment.TickCount; XPathDocument stylesheet = new XPathDocument(embeddedResourceStream); Util.WriteLog(string.Format(CultureInfo.CurrentCulture, "new XPathDocument(1) t={1}", new object[] { resource, Environment.TickCount - num2 })); int num3 = Environment.TickCount; System.Xml.Xsl.XslTransform transform = new System.Xml.Xsl.XslTransform(); transform.Load(stylesheet, resolver, evidence); Util.WriteLog(string.Format(CultureInfo.CurrentCulture, "XslTransform.Load t={1}", new object[] { resource, Environment.TickCount - num3 })); MemoryStream output = new MemoryStream(); Util.CopyStream(input, output); int num4 = Environment.TickCount; XPathDocument document2 = new XPathDocument(output); Util.WriteLog(string.Format(CultureInfo.CurrentCulture, "new XPathDocument(2) t={1}", new object[] { resource, Environment.TickCount - num4 })); XsltArgumentList args = null; if (entries.Length > 0) { args = new XsltArgumentList(); foreach (DictionaryEntry entry in entries) { string name = entry.Key.ToString(); object parameter = entry.Value.ToString(); args.AddParam(name, "", parameter); Util.WriteLog(string.Format(CultureInfo.CurrentCulture, "arg: key='{0}' value='{1}'", new object[] { name, parameter.ToString() })); } } MemoryStream w = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(w, Encoding.UTF8); writer.WriteStartDocument(); int num1 = Environment.TickCount; transform.Transform((IXPathNavigable)document2, args, (XmlWriter)writer, resolver); Util.WriteLog(string.Format(CultureInfo.CurrentCulture, "XslTransform.Transform t={1}", new object[] { resource, Environment.TickCount - num4 })); writer.WriteEndDocument(); writer.Flush(); w.Position = 0L; Util.WriteLog(string.Format(CultureInfo.CurrentCulture, "XslTransform(\"{0}\") t={1}", new object[] { resource, Environment.TickCount - tickCount })); return(w); }
public void WriteToExcel(string Dir, string Filename, string Xslname, string Query, Int16 Limit) { DataSet ds = new DataSet(); // Dim fn, str As String string str = null; long i = 0; long j = 0; //Dim d As Directory j = 0; SqlDataAdapter da = new SqlDataAdapter(Query, con); da.Fill(ds); da.Dispose(); if (!Directory.Exists(Dir)) { Directory.CreateDirectory(Dir); } for (i = 1; i <= ds.Tables[0].Rows.Count; i += Limit) { str = Query + " and num between " + i + " and " + (i + Limit - 1); SqlDataAdapter da1 = new SqlDataAdapter(str, con); DataSet DS2 = new DataSet(); da1.Fill(DS2); XmlDataDocument xdd = new XmlDataDocument(DS2); //Dim xt As New Xsl.XslTransform System.Xml.Xsl.XslTransform xt = new System.Xml.Xsl.XslTransform(); xt.Load(Xslname); FileStream fs = new FileStream(Dir + "\\" + Filename + j + ".xls", System.IO.FileMode.CreateNew, System.IO.FileAccess.Write); XmlUrlResolver rs = new XmlUrlResolver(); rs.Credentials = System.Net.CredentialCache.DefaultCredentials; xt.Transform(xdd, null, fs, rs); fs.Close(); j = j + 1; DS2.Dispose(); } }
private static void GenerateViaXSLT(string xsltFileName, System.Xml.XmlDocument xmlMetaData, string outputFile, params XSLTParam[] @params) { System.Xml.Xsl.XslTransform xslt = new System.Xml.Xsl.XslTransform(); System.Xml.XPath.XPathNavigator xNav; System.IO.StreamWriter streamWriter = null; System.Xml.Xsl.XsltArgumentList args = new System.Xml.Xsl.XsltArgumentList(); try { if (xmlMetaData == null) { xmlMetaData = new System.Xml.XmlDocument(); } foreach (XSLTParam param in @params) { args.AddParam(param.Name, "", param.Value); } xNav = xmlMetaData.CreateNavigator(); streamWriter = new System.IO.StreamWriter(outputFile); xslt.Load(xsltFileName); xslt.Transform(xNav, args, streamWriter, null); } finally { if (streamWriter != null) { streamWriter.Flush(); streamWriter.Close(); } } }
/// <summary> /// Processes requests for the LayerControl. /// </summary> /// <param name="context">HttpContext</param> /// <remarks>This method parses the URL. Gets the model for the LayerControl from the session and then uses that to get the XML. Then the HTML is generated /// by using XSLT transform and returnes back as response. /// </remarks> public void ProcessRequest(HttpContext context) { string _command = context.Request["Command"]; string _uniqueID = context.Request["UniqueID"]; string _mapAlias = context.Request["MapAlias"]; string _mapControlID = context.Request["MapControlID"]; // Get Xslt file name string _xsltFile = context.Request["XsltFile"]; // Get the resource path name passed as data and properly encode it. byte[] buffer = new byte[context.Request.InputStream.Length]; int read = context.Request.InputStream.Read(buffer, 0, (int)context.Request.InputStream.Length); string _resourcePath = System.Text.UTF8Encoding.UTF8.GetString(buffer); string _imgPath = _resourcePath; // Form the full path for xslt file string _xsltPath = context.Server.MapPath(_resourcePath) + "\\" + _xsltFile; LayerControlModel layerModel = LayerControlModel.SetDefaultModelInSession(); switch (_command) { case "GetHTML": XmlDocument treeDoc = layerModel.GetLayerXML(_mapAlias, _uniqueID, _imgPath); // load the xslt file into reader System.IO.TextReader tr = new System.IO.StreamReader(_xsltPath); MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); // Now replace the tags in the xslt file with actual strings from resources string line = ""; while ((line = tr.ReadLine()) != null) { Regex regexp = new Regex("(Treeview2_([0-9]+))"); MatchCollection mc = regexp.Matches(line); for (int i = mc.Count - 1; i >= 0; i--) { Match m = mc[i]; Group g = m.Groups[0]; Capture c = m.Groups[0].Captures[0]; string resName = line.Substring(c.Index, c.Length); if (resName.Equals("Treeview2_3")) { line = line.Replace(resName, Resources.ResourceFolder); } else { string resString = L10NUtils.Resources.GetString(resName); line = line.Replace(resName, resString); } } sw.WriteLine(line); } sw.Flush(); ms.Position = 0; // Use that TextReader as the Source for the XmlTextReader System.Xml.XmlReader xr = new System.Xml.XmlTextReader(ms); // Create a new XslTransform class System.Xml.Xsl.XslTransform treeView = new System.Xml.Xsl.XslTransform(); // Load the XmlReader StyleSheet into the XslTransform class treeView.Load(xr, null, null); StringWriter sw2 = new StringWriter(); XPathNavigator nav = treeDoc.CreateNavigator(); // Do the transform and write to response treeView.Transform(nav, null, sw2, null); context.Response.Write(sw2.ToString()); tr.Close(); sw.Close(); ms.Close(); sw2.Close(); /* * XmlDocument treeDoc = layerModel.GetLayerXML(_mapAlias, _uniqueID, _imgPath); * * XslTransform treeView = new XslTransform(); * treeView.Load(_xsltPath); * * StringWriter sw = new StringWriter(); * * XPathNavigator nav = treeDoc.CreateNavigator(); * * // Do the transform and write to response * treeView.Transform(nav, null, sw, null); * context.Response.Write(sw.ToString()); */ break; } }