public void GenerateOutput( #if VISUALSTUDIO_10_0 ProjectItemElement itemElement, #else BuildItem buildItem, #endif Stream outputStream, IDictionary <string, Stream> inputFormatStreams, string defaultNamespace, IORMGeneratorItemProperties itemProperties) { this.EnsureTransform(); Stream inputStream = inputFormatStreams[this._sourceInputFormat]; XsltArgumentList argumentList = new XsltArgumentList(); argumentList.AddParam("DefaultNamespace", string.Empty, defaultNamespace); argumentList.AddExtensionObject("urn:ORMCustomTool:ItemProperties", itemProperties); string[] referenceFormats = this._referenceInputFormats; if (referenceFormats != null) { for (int i = 0; i < referenceFormats.Length; i++) { string referenceFormat = referenceFormats[i]; Stream referenceStream = inputFormatStreams[referenceFormat]; using (XmlReader referenceReader = XmlReader.Create(referenceStream)) { argumentList.AddParam(referenceFormat, string.Empty, new XPathDocument(referenceReader).CreateNavigator().Select(DocumentElementXPathExpression)); } referenceStream.Seek(0, SeekOrigin.Begin); } } XmlReader inputReader = null; XmlWriter outputWriter = null; try { inputReader = XmlReader.Create(inputStream, XmlReaderSettings); outputWriter = XmlWriter.Create(outputStream, this._xmlWriterSettings); this._transform.Transform(inputReader, argumentList, outputWriter); } finally { if (inputReader != null) { inputReader.Close(); } if (outputWriter != null) { outputWriter.Close(); } inputStream.Seek(0, SeekOrigin.Begin); } }
public void HtmlGeneratedReport() { var htmlGenerator = new HtmlReportGenerator(@"..\..\Xslts\BooksHtmlReport.xslt"); var args = new XsltArgumentList(); args.AddExtensionObject("http://library.by/ext", new XsltExtensions()); var result = htmlGenerator.CreateReport(@"..\..\Sources\books.xml", args, @"..\..\Generated\books.html"); Assert.IsTrue(result); }
/// <summary> /// 根据内容类样式展现HTML /// </summary> /// <returns></returns> public static StringWriter ShowContentLabel(params string[] strString) { StringWriter output = new StringWriter(); try { string LableName = ""; XsltArgumentList argsList = new XsltArgumentList(); argsList.AddExtensionObject("WP:BaseClass", new BaseClass()); LableName = strString[0].Split('=')[1]; string XMLPath = BaseClass.GetContentLabel() + LableName + ".config"; string LableSqlString = XMLExplainer.GetXMLValue("root", "LabelSqlString", XMLPath); string XsltString = XMLExplainer.GetXMLValue("root", "LabelTemplate", XMLPath); for (int i = 1; i < strString.Length; i++) { string strObject = strString[i]; string[] strObjects = strObject.Split('='); LableSqlString = LableSqlString.Replace("@" + strObjects[0], strObjects[1]); argsList.AddParam(strObjects[0], "", strObjects[1]); } DataTable DT = XMLExplainer.GetXMLValues("attributes", XMLPath); for (int i = 0; i < DT.Rows.Count; i++) { LableSqlString = LableSqlString.Replace("@" + DT.Rows[i]["name"].ToString(), DT.Rows[i]["default"].ToString()); string tempstring = (string)argsList.GetParam(DT.Rows[i]["name"].ToString(), ""); if ("".Equals(tempstring) || tempstring == null) { argsList.AddParam(DT.Rows[i]["name"].ToString(), "", DT.Rows[i]["default"].ToString()); } } XDocument source = new XDocument(); XDocument newTree = new XDocument(); using (XmlWriter writer = newTree.CreateWriter()) { XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(XmlReader.Create(new StringReader(XsltString))); DataTable DTT = PersistenceLayer.Query.ProcessSql(LableSqlString, Names.DBName); DataSet DS = new DataSet(); DS.Tables.Add(DTT); string XmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"; XmlStr = XmlStr + DS.GetXml().ToString(); XmlDocument XmlDoc = new XmlDocument(); XmlDoc.LoadXml(XmlStr); XPathNavigator navgator = XmlDoc.CreateNavigator(); xslt.Transform(navgator, argsList, output); return(output); } } catch (Exception ex) { output.Write(ex.Message.ToString()); return(output); } }
public void XslExtensionObjects() { var xsl = new XslCompiledTransform(); var args = new XsltArgumentList(); args.AddExtensionObject("http://epam.com/xsl/ext", new Counters()); xsl.Load("02_ExtensionObjects.xslt"); xsl.Transform("CDCatalog1.xml", args, Console.Out); }
private void DocumentFunction(XmlElement functionElement, NAntXsltUtilities utilities) { if (functionElement == null) { throw new ArgumentNullException("functionElement"); } string methodID = functionElement.GetAttribute("id"); string filename = utilities.GetFileNameForFunction(functionElement, false); XsltArgumentList arguments = CreateXsltArgumentList(); arguments.AddParam("method-id", string.Empty, methodID); arguments.AddParam("refType", string.Empty, "Function"); arguments.AddParam("functionName", string.Empty, functionElement.GetAttribute("name")); // add extension object to Xslt arguments arguments.AddExtensionObject("urn:NAntUtil", utilities); // document parameter types foreach (XmlAttribute paramTypeAttribute in functionElement.SelectNodes("parameter/@type")) { string paramType = "T:" + paramTypeAttribute.Value; XmlNode typeNode = utilities.GetTypeNodeByID(paramType); if (typeNode != null) { ElementDocType paramDocType = utilities.GetElementDocType(typeNode); if (paramDocType != ElementDocType.None) { DocumentType(typeNode, paramDocType, utilities); } } } // document return type XmlAttribute returnTypeAttribute = functionElement.Attributes["returnType"]; if (returnTypeAttribute != null) { string returnType = "T:" + returnTypeAttribute.Value; XmlNode returnTypeNode = utilities.GetTypeNodeByID(returnType); if (returnTypeNode != null) { ElementDocType returnDocType = utilities.GetElementDocType(returnTypeNode); if (returnDocType != ElementDocType.None) { DocumentType(returnTypeNode, returnDocType, utilities); } } } // create the page TransformAndWriteResult(_xsltFunctionDoc, arguments, filename); }
public static XDocument Transform(XNode document, XElement xsltDocument) { var args = new XsltArgumentList(); var extensionFunctions = new XsltFunctions(); args.AddExtensionObject("xalan://diadem.dirigent.plugin.helpers.XsltFunctions", extensionFunctions); var transformedDocument = Transform(document, args, xsltDocument); var debugMessage = new XElement("DebugMessage", extensionFunctions.DebugMessage.ToString()); return(transformedDocument); }
public void Transform(string inputPath, string outputPath) { var args = new XsltArgumentList(); args.AddExtensionObject(_rssDateTransformer, new RssDateTransformer()); var xsl = new XslCompiledTransform(); xsl.Load(_stylesheet); xsl.Transform(inputPath, args, new FileStream(outputPath, FileMode.Create)); }
/// <summary> /// A generic XSL Transformation [v1.0] Class for use in ASP.NET pages /// </summary> public static string TransformXml(string xmlPath, string xsltPath, Hashtable xsltParams, Hashtable xsltObjects, string output) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); try { XPathDocument doc = new XPathDocument(xmlPath); XsltArgumentList args = new XsltArgumentList(); // Create the XsltSettings object with script enabled. XsltSettings settings = new XsltSettings(false, true); settings.EnableDocumentFunction = true; XslCompiledTransform xslDoc = new XslCompiledTransform(); xslDoc.Load(xsltPath, settings, new XmlUrlResolver()); //Fill XsltArgumentList if necessary - taken from key/value pairs in the hashtable if (xsltParams != null) { IDictionaryEnumerator pEnumerator = xsltParams.GetEnumerator(); while (pEnumerator.MoveNext()) { args.AddParam(pEnumerator.Key.ToString(),"", pEnumerator.Value); } } //Fill XSL objects - not used this so pass through null if (xsltObjects != null) { IDictionaryEnumerator pEnumerator = xsltObjects.GetEnumerator(); while (pEnumerator.MoveNext()) { args.AddExtensionObject(pEnumerator.Key.ToString(), pEnumerator.Value); } } xslDoc.Transform(doc,args,sw); if (output == "file") { TextWriter w = new StreamWriter(@"c:\output.html"); w.Write(sb.ToString()); w.Close(); } return sb.ToString(); } catch (Exception exp) { return exp.ToString(); } finally { sw.Close(); } }
public static string Transform(string strXml, string skinfile, bool enableScript) { string re = ""; if (Request.Int("debug") == 1) { XmlDocument xml = new XmlDocument(); xml.LoadXml(strXml); re = xml.DocumentElement.OuterXml; } else { XslCompiledTransform xslt = new XslCompiledTransform(); if (enableScript) { XsltSettings xsltsetting = new XsltSettings(); xsltsetting.EnableScript = true; xslt.Load(skinfile, xsltsetting, new XmlUrlResolver()); } else { xslt.Load(skinfile); } StringBuilder sb = new StringBuilder(); XmlWriterSettings mysetting = new XmlWriterSettings(); mysetting.Indent = true; mysetting.IndentChars = " "; mysetting.ConformanceLevel = ConformanceLevel.Auto; XmlWriter writer = XmlWriter.Create(sb, mysetting); XsltArgumentList argsList = new XsltArgumentList(); Tools tools = new Tools(); argsList.AddExtensionObject("urn:Tools", tools); XmlDocument xml = new XmlDocument(); xml.LoadXml(strXml); xslt.Transform(xml, argsList, writer); re = sb.ToString(); //特殊字符处理(Start) if (re.StartsWith("<?xml version=\"1.0\" encoding=\"utf-16\"?>")) { re = re.Substring(39); } re = re.Replace(" xmlns:Tools=\"urn:Tools\">", ">"); re = re.Replace(" xmlns:Tools=\"urn:Tools\" />", " />"); if (re.StartsWith("<html xmlns=\"http://www.w3.org/1999/xhtml\">")) { re = "<!doctype html public \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + re; } //特殊字符处理(End) } return(re); }
private static void ApplyXsltExtensionObjectOverridesToXsltArguments(XsltArgumentList transformArgs, IEnumerable <XsltExtensionObjectDescriptor> xsltExtensionObjectOverrides, TransformBase map) { var xsltArgumentListContent = XElement.Parse(map.XsltArgumentListContent); foreach (var item in xsltExtensionObjectOverrides) { var name = FindNamespaceForXsltExtensionObjectType(xsltArgumentListContent, item.ClassType); transformArgs.RemoveExtensionObject(name); transformArgs.AddExtensionObject(name, item.Instance); } }
private XsltArgumentList CreateXsltArguments(string filename) { XsltArgumentList xsltArguments = null; XsltExtension xsltExtension = new XsltExtension(_catalogosPath); xsltArguments = new XsltArgumentList(); xsltArguments.AddExtensionObject("urn:actl-xslt", xsltExtension); xsltArguments.AddParam("nombreArchivoEnviado", "", filename); return(xsltArguments); }
static void Main(string[] args) { XslCompiledTransform proc = new XslCompiledTransform(); proc.Load("../../XSLTFile1.xslt"); XsltArgumentList xsltArgs = new XsltArgumentList(); xsltArgs.AddExtensionObject("http://example.com/mf", new Test1()); proc.Transform("../../XMLFile1.xml", xsltArgs, Console.Out); }
public static void Transform(string xsltFile, string xmlFile) { var transform = new XslCompiledTransform(); var args = new XsltArgumentList(); args.AddExtensionObject("http://epam.com/xslt/ext", new XsltTransformHelper()); transform.Load(xsltFile); using (var writer = XmlWriter.Create("result.html")) { transform.Transform(xmlFile, args, writer); } }
/// <summary> /// Transform argument through XSL /// </summary> /// <param name="filename">Source AXL file name</param> /// <param name="stylesheet">XSLT Stylesheet file</param> /// <param name="outfilename">Output File Name</param> /// <param name="arg">Current argument</param> /// <returns></returns> public bool doTransform(string filename, string stylesheet, string outfilename, Argument arg) { StringBuilder sb; XPathDocument xpathdocument; // Get output path outfilepath = System.IO.Path.GetDirectoryName(outfilename); if (outfilepath.IndexOf('\\') >= 0) { outfilepath += '\\'; } // Send text to outfilename, a text file StreamWriter sw = new StreamWriter(outfilename); // //XslTransform xslt = new XslTransform(); XslCompiledTransform xslt = new XslCompiledTransform(); if (filename == null | filename.Equals("")) // empty string means read from current XML { // load current argument into the string sb = arg.writeArgumentXMLstring(arg.findHead(), true); xpathdocument = new XPathDocument(new XmlTextReader(new StringReader(sb.ToString()))); } else { xpathdocument = new XPathDocument(filename); } XmlTextReader xtr = new XmlTextReader(stylesheet); xslt.Load(xtr, null, null); XmlTextWriter writer = new XmlTextWriter(sw); writer.Formatting = Formatting.Indented; // Create an XsltArgumentList. XsltArgumentList xslArg = new XsltArgumentList(); // Add an object to create image TODO Possible error - Current argument can only have a transformed image ImageXSLextension obj = new ImageXSLextension(arg, this.outfilepath); xslArg.AddExtensionObject("urn:image", obj); xslt.Transform(xpathdocument, xslArg, writer); // xslt.Transform(xpathdocument, writer); xtr.Close(); sw.Close(); return(true); }
public string Htmlize(XmlReader ecma_xml, Dictionary <string, string> extraArgs) { var args = new XsltArgumentList(); args.AddExtensionObject("monodoc:///extensions", ExtObject); foreach (var kvp in extraArgs) { args.AddParam(kvp.Key, string.Empty, kvp.Value); } return(Htmlize(ecma_xml, args)); }
private XElement EnrichXml(IProcessingContext context, XElement nodes) { XDocument ret = new XDocument(); XmlWriter nodeWriter = ret.CreateWriter(); XsltArgumentList argList = new XsltArgumentList(); argList.AddExtensionObject("urn:lostdoc-core", new AssetVersionResolver(context, null)); this._xslTransform.Transform(nodes.CreateNavigator(), argList, nodeWriter); nodeWriter.Close(); return(ret.Root); }
public void Transform(string contentId, string metadataXml, string annotationsXml, string versionId, Content contentDataSet) { XsltArgumentList arguments = new XsltArgumentList(); Link link = new Link(contentDataSet, links); XmlDocument metadata = new XmlDocument(); XmlDocument annotations = new XmlDocument(); string filename = Path.Combine(withinChmDir, contentId + ".htm"); StreamReader sr = new StreamReader(filename); int codePage = new CultureInfo(locale).TextInfo.ANSICodePage; // We use these fallbacks because is unknown under DBCS like Japanese // and translated to ? by default. Encoding encoding = Encoding.GetEncoding(codePage, new EncoderReplacementFallback(" "), new DecoderReplacementFallback(" ")); string xml = sr.ReadToEnd(); sr.Close(); metadata.LoadXml(metadataXml); annotations.LoadXml(annotationsXml); arguments.AddParam("metadata", "", metadata.CreateNavigator()); arguments.AddParam("annotations", "", annotations.CreateNavigator()); arguments.AddParam("version", "", versionId); arguments.AddParam("locale", "", locale); arguments.AddParam("charset", "", encoding.WebName); arguments.AddExtensionObject("urn:Link", link); TextReader tr = new StringReader(xml); XmlReader xr = XmlReader.Create(tr); using (StreamWriter sw = new StreamWriter(filename, false, encoding)) { try { xform.Transform(xr, arguments, sw); } catch (Exception ex) { return; } } }
public MessagesReader( MediaBasedReaderParams readerParams, XmlFormatInfo fmt, IRegexFactory regexFactory, ITraceSourceFactory traceSourceFactory ) : base(readerParams.Media, fmt.BeginFinder, fmt.EndFinder, fmt.ExtensionsInitData, fmt.TextStreamPositioningParams, readerParams.Flags, readerParams.SettingsAccessor) { this.formatInfo = fmt; this.threads = readerParams.Threads; this.traceSourceFactory = traceSourceFactory; this.regexFactory = regexFactory; this.transformArgs = new XsltArgumentList(); this.xslExt = new LogJointXSLExtension(); transformArgs.AddExtensionObject(Properties.LogJointNS, this.xslExt); foreach (MessagesReaderExtensions.ExtensionData extInfo in this.Extensions.Items) { transformArgs.AddExtensionObject(Properties.LogJointNS + extInfo.Name, extInfo.Instance()); } }
public static string Transform(string xmlStylesheetPath, string xmlDocumentPath, IEnumerable <object> arguments) { var xsltArgumentList = new XsltArgumentList(); foreach (var argument in arguments.Where(a => a != null)) { var element = (argument is XDocument) ? (argument as XDocument)?.Root : (argument as XElement); if (element != null) { var navigator = element.CreateNavigator(); xsltArgumentList.AddParam(element.Name.LocalName, element.Name.NamespaceName, navigator); } else if (argument is XPathNavigator) { var navigator = argument as XPathNavigator; xsltArgumentList.AddParam(navigator.Name, navigator.NamespaceURI, navigator); } else if (argument is KeyValuePair <string, object> ) { var item = (KeyValuePair <string, object>)argument; xsltArgumentList.AddExtensionObject(item.Key, item.Value); } else { xsltArgumentList.AddExtensionObject(argument.GetXmlNamespace(), argument); } } var transform = new XslCompiledTransform(true); transform.Load(xmlStylesheetPath); using var outStream = new MemoryStream(); using var writer = new StreamWriter(outStream); transform.Transform(xmlDocumentPath, xsltArgumentList, writer); var result = Encoding.UTF8.GetString(outStream.ToArray()); return(result); }
public XmlDocument Transform() { if (LastTransformer != null) { XsltArgumentList xal = new XsltArgumentList(); xal.AddExtensionObject(XsltExtensions.XsltStringExtensions.Namespace, new XsltExtensions.XsltStringExtensions()); //This is to make the "easy" extension functions available... StringBuilder xmlSB = new StringBuilder(); XmlWriter xWriter = XmlWriter.Create(xmlSB); LastTransformer.Transform(this, xal, xWriter); LoadXml(xmlSB.ToString()); } return(this); }
static void Main() { XsltArgumentList args = new XsltArgumentList(); args.AddExtensionObject("my-namespace", new MyExtensionObject()); XslTransform xslt = new XslTransform(); xslt.Load("foo.xslt"); using (TextWriter output = File.CreateText("out.txt")) { XPathDocument input = new XPathDocument("foo.xml"); xslt.Transform(input, args, output); } }
public virtual void RenderHtml(TextWriter writer, XPathDocument xmlDoc) { // Transform XLST validation xsltFileFull = Xslt; if (!xsltFileFull.Contains(@":\") && Context != null) { xsltFileFull = Context.Server.MapPath(dirXslt + Xslt); } Trace.Write("Transform ID=" + this.ID, "xslt=" + xsltFileFull); XsltArgumentList xslArg = new XsltArgumentList(); XslCompiledTransform trans = new XslCompiledTransform(); if (Context != null && Xslt.Length > 0 && File.Exists(xsltFileFull)) { #if WEB string serverUrl = Context.Request.Url.Scheme + "://" + Context.Request.Url.Authority + "/"; #else string serverUrl = Context.Request.Url.Scheme + "://" + Context.Request.Url.Authority + "/"; // serverUrl = Context.Request.QueryString; #endif XsltIncludeResolver resolver = new XsltIncludeResolver(serverUrl); // for <xsl:include> trans.Load(xsltFileFull, XsltSettings.TrustedXslt, resolver as XmlUrlResolver); } else { var reader = XmlReader.Create(System.IO.File.OpenRead(xsltFileFull)); trans.Load(stylesheet: reader); } Trace.Write("Transform ID=" + this.ID, "XSLT Parse Test OK"); // Add an object to convert RequestInfo info = null; if (Context != null) { info = new RequestInfo(this, Context.Request); } else { info = new RequestInfo(this, null); } xslArg.AddExtensionObject("urn:request-info", info); if (isDebug <= 1) { trans.Transform(xmlDoc, xslArg, writer); } }
public static bool SendEmail(SPWeb web, string emailTo, string xslt, IDictionary xslValues) { XmlDocument xmlDoc; XPathNavigator xpathNavigator; XslCompiledTransform xslEmailTransform = new XslCompiledTransform(); XsltArgumentList xslArguments; StringBuilder sbEmail; XmlTextWriter xmlWriter; XmlNode xmlNodeTitle; XmlDocument xmlEmail; XsltSettings settings = new XsltSettings(true, true); XmlUrlResolver resolver = new XmlUrlResolver(); string subject = string.Empty; try { xslEmailTransform.Load(new XmlTextReader(xslt, XmlNodeType.Document, null), settings, resolver); xmlDoc = new XmlDocument(); xmlDoc.AppendChild(xmlDoc.CreateElement("DocumentRoot")); xpathNavigator = xmlDoc.CreateNavigator(); xslArguments = new XsltArgumentList(); if (xslValues != null) { foreach (DictionaryEntry xslEntry in xslValues) { xslArguments.AddExtensionObject(xslEntry.Key.ToString(), xslEntry.Value); } } sbEmail = new StringBuilder(); xmlWriter = new XmlTextWriter(new StringWriter(sbEmail)); xslEmailTransform.Transform(xpathNavigator, xslArguments, xmlWriter); xmlEmail = new XmlDocument(); xmlEmail.LoadXml(sbEmail.ToString()); xmlNodeTitle = xmlEmail.SelectSingleNode("//title"); subject = xmlNodeTitle.InnerText; return(SendEmail(web, emailTo, subject, sbEmail.ToString())); } catch (Exception ex) { Utils.LogError(ex); return(false); } }
public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress) { try { XmlDocument source = new XmlDocument(); source.LoadXml(bstrInputFileContents); string xsltFileName = source.DocumentElement.GetAttribute("generator"); if (xsltFileName == null || xsltFileName == "") { xsltFileName = "ModelGenerator.xslt"; } string xsltFile = wszInputFilePath.Split(new string[] { "Schema" }, StringSplitOptions.None)[0] + @"Schema\XsltGenerator\" + xsltFileName; if (!File.Exists(xsltFile)) { throw new ApplicationException("Xslt file not exists: " + xsltFile); } XslCompiledTransform transformator = new XslCompiledTransform(); transformator.Load(xsltFile); string rootPath = Path.GetFullPath(wszInputFilePath); rootPath = rootPath.Substring(0, rootPath.LastIndexOf('\\') + 1); XsltUtil util = new XsltUtil(rootPath, "ConnectionString"); XsltArgumentList args = new XsltArgumentList(); args.AddParam("param_namespace", "", wszDefaultNamespace); args.AddExtensionObject("urn:util", util); using (MemoryStream stream = new MemoryStream()) { transformator.Transform(source, args, stream); stream.Position = 0; byte[] content = stream.ToArray(); pcbOutput = (uint)content.Length; rgbOutputFileContents[0] = Marshal.AllocCoTaskMem((int)content.Length); Marshal.Copy(content, 0, rgbOutputFileContents[0], (int)content.Length); } } catch (Exception ex) { byte[] content = Encoding.UTF8.GetBytes(ex.ToString()); pcbOutput = (uint)content.Length; rgbOutputFileContents[0] = Marshal.AllocCoTaskMem((int)content.Length); Marshal.Copy(content, 0, rgbOutputFileContents[0], (int)content.Length); } return(VSConstants.S_OK); }
public static XsltArgumentList GetXsltArgumentList(XSLTExtensionType t, string sourceXml) { switch ((int)t) { default: case 0: return(null); case 1: XsltArgumentList list = new XsltArgumentList(); list.AddExtensionObject("urn:xdsgw:XmlNodeTransformer", new XmlNodeTransformer(sourceXml)); return(list); } }
private string ImportShipment() { if (Request.Files.Count > 0) { HttpPostedFile PostedFile = Request.Files[0]; if (!PostedFile.FileName.EndsWith("csv", StringComparison.InvariantCultureIgnoreCase) && !PostedFile.FileName.EndsWith("xml", StringComparison.InvariantCultureIgnoreCase) && PostedFile.FileName.Trim() != "") { errors = String.Format(AppLogic.GetString("admin.OrderShipment2.InvalidFileType", SkinID, LocaleSetting), CommonLogic.IIF(PostedFile.ContentLength == 0, AppLogic.GetString("admin.common.FileContentsWereEmpty", SkinID, LocaleSetting), AppLogic.GetString("admin.common.CommaDelimitedFilesPrompt", SkinID, LocaleSetting))); } else { string xml = String.Empty; string filename = "Import_ASPDNSF"; string FullFilePath = CommonLogic.SafeMapPath("../images") + "\\" + filename + PostedFile.FileName.ToLowerInvariant().Substring(PostedFile.FileName.ToLowerInvariant().LastIndexOf('.')); PostedFile.SaveAs(FullFilePath); StreamReader sr = new StreamReader(FullFilePath); string filecontent = sr.ReadToEnd(); sr.Close(); if (PostedFile.FileName.EndsWith("csv", StringComparison.InvariantCultureIgnoreCase)) { xml = ImportXmlData(filecontent); } else if (PostedFile.FileName.EndsWith("xls", StringComparison.InvariantCultureIgnoreCase)) { xml = Import.ConvertPricingFileToXml(FullFilePath); XslCompiledTransform xForm = new XslCompiledTransform(); xForm.Load(CommonLogic.SafeMapPath("XmlPackages/ExcelPricingImport.xslt")); Localization ExtObj = new Localization(); XsltArgumentList m_TransformArgumentList = new XsltArgumentList(); m_TransformArgumentList.AddExtensionObject("urn:aspdnsf", ExtObj); XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(xml); StringWriter xsw = new StringWriter(); xForm.Transform(xdoc, m_TransformArgumentList, xsw); xml = xsw.ToString(); } else { xml = filecontent; } File.Delete(FullFilePath); errors = ImportProductList(xml); return(getImportedOrderNumbers(xml)); } } return(""); }
private XElement EnrichXml(IProcessingContext context, Assembly hintAssembly, XElement nodes) { XDocument ret = new XDocument(); using (XmlWriter nodeWriter = ret.CreateWriter()) { XsltArgumentList argList = new XsltArgumentList(); argList.AddExtensionObject(Namespaces.TemplateExtensions, new AssetVersionResolver(context, hintAssembly)); this._xslTransform.Transform(nodes.CreateNavigator(), argList, nodeWriter); nodeWriter.Close(); } return(ret.Root); }
protected void TransformButton_Click(object sender, EventArgs e) { XsltArgumentList args = new XsltArgumentList(); XslCompiledTransform xsl = new XslCompiledTransform(); args.AddExtensionObject(ExtensionDemo.Namespace, new ExtensionDemo()); xsl.Load(Server.MapPath("Xml/flights-html.xsl")); Response.Clear(); Response.ContentType = "text/xml"; xsl.Transform(Server.MapPath("Xml/Flights.xml"), args, Response.OutputStream); Response.End(); }
public static void Transform(string sXmlPath, string sXslPath) { try { XPathDocument myXPathDoc = new XPathDocument(sXmlPath); XslCompiledTransform myXslTrans = new XslCompiledTransform(); myXslTrans.Load(sXslPath); XsltArgumentList xslArgs = new XsltArgumentList(); Utils classPtr = new Utils(); xslArgs.AddExtensionObject("urn:util", classPtr); XmlTextWriter myWriter = new XmlTextWriter("result.xml", null); myXslTrans.Transform(myXPathDoc, xslArgs, myWriter); myWriter.Close(); } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } }
public virtual void AddRequestInfo(XsltArgumentList xslArg) { // Add an object to convert RequestInfo info = null; if (Context != null) { info = new RequestInfo(this, Context.Request); } else { info = new RequestInfo(this, null); } xslArg.AddExtensionObject("urn:request-info", info); }
public static void Transform(string sXmlPath, string sXslPath) { try { XPathDocument myXPathDoc = new XPathDocument(sXmlPath); XslCompiledTransform myXslTrans = new XslCompiledTransform(); myXslTrans.Load(sXslPath); XsltArgumentList xslArgs = new XsltArgumentList(); Utils classPtr = new Utils(); xslArgs.AddExtensionObject("urn:util", classPtr); XmlTextWriter myWriter = new XmlTextWriter("result.xml", null); myXslTrans.Transform(myXPathDoc, xslArgs, myWriter); myWriter.Close(); } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } }
public void TransformXml(string[] parts) { XsltSettings XSLSettings = new XsltSettings(); XSLSettings.EnableDocumentFunction = true; XmlUrlResolver resolver = new XmlUrlResolver(); XslCompiledTransform xsl = new XslCompiledTransform(); xsl.Load(root + "/templates/global.xsl", XSLSettings, resolver); timmie.timmie timmie = new timmie.timmie(); XsltArgumentList args = new XsltArgumentList(); args.AddExtensionObject(timmie.nameSpaceURI, timmie); xsl.Transform(CreateContext(parts), args, HttpContext.Current.Response.Output); }
private XElement UpdateTreeView(XElement functionMarkupContainer) { // TODO: Do some compiled xslt caching XElement treeInput = CopyWithId(functionMarkupContainer); treeInput.Add(GetFunctionDescriptionElements(functionMarkupContainer)); if (_state.AllowSelectingInputParameters) { CollapseGetInputParamaterFunctionCalls(treeInput, InputParameterNodeIDs); } // treeInput.Save(Request.MapPath("out.tmp.xml")); string xslFilePath = Request.MapPath("functioneditortree.xslt"); XslCompiledTransform transform = GetTransformation(xslFilePath); var xsltTransformArguments = new XsltArgumentList(); xsltTransformArguments.AddExtensionObject(XsltExtensionObjectNamespace, new TreeRenderingXsltExtensionObject(TreePathToIdMapping)); xsltTransformArguments.AddParam("SelectedId", string.Empty, SelectedNode.IsNullOrEmpty() ? string.Empty : TreePathToIdMapping[SelectedNode]); XDocument transformedDoc = new XDocument(); using (XmlWriter writer = transformedDoc.CreateWriter()) { transform.Transform(treeInput.CreateReader(), xsltTransformArguments, writer); } WriteTo(transformedDoc, this.TreePlaceholder); return treeInput; }
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); }