static XsltSettings () { defaultSettings = new XsltSettings (true); trustedXslt = new XsltSettings (true); trustedXslt.enableDocument = true; trustedXslt.enableScript = true; }
public void XsltSettings1_1(object param0, object param1, object param2, object param3, object param4) { Init(param1.ToString(), param2.ToString()); // In Proc Skip // XsltSettings - Debug (1-20) // XsltSettings - Retail (1,4,9,11,15,16,19,20) XsltSettings xs = new XsltSettings((bool)param3, (bool)param4); _xsl.Load(_xslFile, xs, new XmlUrlResolver()); try { StringWriter sw = Transform(); switch ((int)param0) { case 1: case 4: VerifyResult(sw.ToString(), "30", "Unexpected result, expected 30"); return; case 5: case 8: VerifyResult(sw.ToString(), "7", "Unexpected result, expected 7"); return; case 9: VerifyResult(sw.ToString(), "17", "Unexpected result, expected 17"); return; case 13: case 14: VerifyResult(sw.ToString(), "PASS", "Unexpected result, expected PASS"); return; default: Assert.True(false); return; } } catch (XsltException ex) { switch ((int)param0) { case 2: case 3: case 6: case 7: case 10: case 11: case 12: _output.WriteLine(ex.ToString()); _output.WriteLine(ex.Message); return; default: Assert.True(false); return; } } }
private void Transform() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Transforming: {0}", this.XmlFile)); XDocument xslDoc; if (!string.IsNullOrEmpty(this.XslTransformFile) && !File.Exists(this.XslTransformFile)) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "XslTransformFile not found: {0}", this.XslTransformFile)); return; } if (!string.IsNullOrEmpty(this.XslTransformFile)) { // Load the XslTransformFile this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Loading XslTransformFile: {0}", this.XslTransformFile)); xslDoc = XDocument.Load(this.XslTransformFile); } else if (!string.IsNullOrEmpty(this.XslTransform)) { // Load the XslTransform this.LogTaskMessage(MessageImportance.Low, "Loading XslTransform"); using (StringReader sr = new StringReader(this.XslTransform)) { xslDoc = XDocument.Load(sr); } } else { this.Log.LogError("XslTransform or XslTransformFile must be specified"); return; } // Load the style sheet. XslCompiledTransform xslt = new XslCompiledTransform(); XsltSettings settings = new XsltSettings { EnableScript = true }; using (StringReader sr = new StringReader(xslDoc.ToString())) { xslt.Load(XmlReader.Create(sr), settings, null); StringBuilder builder = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(builder, xslt.OutputSettings)) { this.LogTaskMessage(MessageImportance.Low, "Running XslTransform"); // Execute the transform and output the results to a writer. xslt.Transform(this.xmlDoc.CreateReader(), writer); } this.Output = builder.ToString(); } if (!string.IsNullOrEmpty(this.OutputFile)) { if (xslt.OutputSettings.OutputMethod == XmlOutputMethod.Text) { this.LogTaskMessage(MessageImportance.Low, "Writing using text method"); using (FileStream stream = new FileStream(this.OutputFile, FileMode.Create)) { StreamWriter streamWriter = null; try { streamWriter = new StreamWriter(stream, Encoding.Default); // Output the results to a writer. streamWriter.Write(this.Output); } finally { if (streamWriter != null) { streamWriter.Close(); } } } } else { this.LogTaskMessage(MessageImportance.Low, "Writing using XML method"); using (StringReader sr = new StringReader(this.Output)) { XDocument newxmlDoc = XDocument.Load(sr); if (!string.IsNullOrEmpty(this.OutputFile)) { XmlWriterSettings writerSettings = new XmlWriterSettings { ConformanceLevel = this.conformanceLevel, Encoding = this.fileEncoding, Indent = this.Indent, OmitXmlDeclaration = this.OmitXmlDeclaration, CloseOutput = true }; using (XmlWriter xw = XmlWriter.Create(this.OutputFile, writerSettings)) { if (xw != null) { newxmlDoc.WriteTo(xw); } else { Log.LogError("There was an error creating the XmlWriter for the OutputFile"); return; } } } } } } }
/// <summary> /// Apply a map to a xml message /// </summary> /// <param name="mapFullName">Map full name (Class, strong name)</param> /// <param name="messageIn">Xml message to be transformed</param> /// <returns>The transformed xml document</returns> public static TransformResults Transform(string mapFullName, XmlDocument messageIn) { if (string.IsNullOrWhiteSpace(mapFullName)) { return(new TransformResults()); } var msgOut = new XmlDocument(); StringWriter writer = null; Debug.Write("[Resolver] Transform using the map in " + mapFullName); // Check parameters if (messageIn == null) { throw new ArgumentNullException("messageIn"); } if (string.IsNullOrEmpty(mapFullName)) { throw new ArgumentNullException("mapFullName"); } // Extract the class name and the strong name from the MapFullName var className = mapFullName.Split(',')[0]; var pos = mapFullName.IndexOf(','); if (pos == -1) { throw new ArgumentException(string.Format(Resources.ExceptionMapFullName, mapFullName)); } var strongName = mapFullName.Substring(pos); strongName = strongName.Trim(); if (strongName.StartsWith(",")) { strongName = strongName.Substring(1); } strongName = strongName.Trim(); TransformResults transformResults; try { // Load the map var mapAssembly = Assembly.Load(strongName); var map = mapAssembly.CreateInstance(className); if (map == null) { throw new EsbResolutionException( string.Format(Resources.ExceptionMapClassInvalid, className)); } // Extract the xslt var xmlContentProp = map.GetType().GetProperty("XmlContent"); var xsl = xmlContentProp.GetValue(map, null); // Extract xsl and extension objects var xsltArgumentsProp = map.GetType().GetProperty("XsltArgumentListContent"); var xsltArguments = xsltArgumentsProp.GetValue(map, null); // Extract source schemas var sourceSchemasProp = map.GetType().GetProperty("SourceSchemas"); var sourceSchemas = (string[])sourceSchemasProp.GetValue(map, null); // Extract target schemas var targetSchemasProp = map.GetType().GetProperty("TargetSchemas"); var targetSchemas = (string[])targetSchemasProp.GetValue(map, null); // Load all the external assemblies var xmlExtension = new XmlDocument(); var xslArgList = new XsltArgumentList(); if (xsltArguments != null) { // Load the argument list and create all the needed instances xmlExtension.LoadXml(xsltArguments.ToString()); var xmlExtensionNodes = xmlExtension.SelectNodes(Resources.XPathExtensionObject); if (xmlExtensionNodes != null) { foreach (XmlNode extObjNode in xmlExtensionNodes) { var extAttributes = extObjNode.Attributes; if (extAttributes == null) { continue; } var namespaceNode = extAttributes.GetNamedItem("Namespace"); var assemblyNode = extAttributes.GetNamedItem("AssemblyName"); var classNode = extAttributes.GetNamedItem("ClassName"); var extAssembly = Assembly.Load(assemblyNode.InnerText); var extObj = extAssembly.CreateInstance(classNode.InnerText); if (extObj != null) { xslArgList.AddExtensionObject(namespaceNode.InnerText, extObj); } } } } // Apply xsl to msg in var xslDoc = new XmlDocument(); xslDoc.LoadXml(xsl.ToString()); var settings = new XsltSettings(true, true); var xlsTrans = new XslCompiledTransform(); xlsTrans.Load(xslDoc, settings, new XmlUrlResolver()); writer = new StringWriter(); if (messageIn.DocumentElement != null) { xlsTrans.Transform(new XmlNodeReader(messageIn.DocumentElement), xslArgList, writer); } writer.Flush(); try { // Return the msg out msgOut.LoadXml(writer.ToString()); } catch (Exception) { // Log the error here with useful information! If the map fails (e.g., the wrong // map is configured in the Service Mediation policy) the Load may fail with an unhelpful // 'Root not missing' error. We need to log an additional error here that records what // map was being applied. var inMessageType = messageIn.DocumentElement == null ? "<source message is empty>" : string.Format( "{0}#{1}", messageIn.DocumentElement.NamespaceURI, messageIn.DocumentElement.LocalName); var message = string.Format( "A transformation failed for map {0} and message of type {1}. Is the correct map configured in the ESB service mediation policy?", mapFullName, inMessageType); EventLog.WriteEntry("Application", message, EventLogEntryType.Error, 3); throw; } transformResults = new TransformResults(messageIn, msgOut, xslDoc, xslArgList, sourceSchemas, targetSchemas, (from schemaName in targetSchemas select SchemaStrongNameCache.GetSchemaStrongName(map.GetType(), schemaName)).ToList()); } finally { if (writer != null) { writer.Close(); } } return(transformResults); }
public void Load(System.Xml.XPath.IXPathNavigable stylesheet, XsltSettings settings, System.Xml.XmlResolver stylesheetResolver) { }
public static System.CodeDom.Compiler.CompilerErrorCollection CompileToType(System.Xml.XmlReader stylesheet, XsltSettings settings, System.Xml.XmlResolver stylesheetResolver, bool debug, System.Reflection.Emit.TypeBuilder typeBuilder, string scriptAssemblyPath) { }
public static XslCompiledTransform CompileTransform(XmlReader stylesheetReader, XsltSettings settings = null, XmlUrlResolver resolver = null) { settings = settings ?? new XsltSettings(true, true); resolver = resolver ?? new XmlUrlResolver(); XslCompiledTransform compiledTransform = new XslCompiledTransform(); compiledTransform.Load(stylesheetReader, settings, resolver); return(compiledTransform); }
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); }
static void Main(string[] args) { if ((args.Length < 2) || (args.Length > 2)) { Console.WriteLine("Syntax:\r\n\r\nsitegenerator source-path target-path\r\n"); return; } string sourceDirectory = args[0]; string websiteDirectory = args[1]; if (!Directory.Exists(sourceDirectory)) { Console.WriteLine("Error: Source path not found\n\n"); } if (!Directory.Exists(websiteDirectory)) { Console.WriteLine("Error: Target path not found\n\n"); } Console.WriteLine("Source: {0}\nTarget: {1}", sourceDirectory, websiteDirectory); string sourceConfigDirectory = Path.Combine(sourceDirectory, "config"); string sourcePageDirectory = Path.Combine(sourceDirectory, "pages"); Helpers.CopyDirectoryFiles(Path.Combine(sourceDirectory, "css"), Path.Combine(websiteDirectory, "css"), true); Helpers.CopyDirectoryFiles(Path.Combine(sourceDirectory, "js"), Path.Combine(websiteDirectory, "js"), true); Helpers.CopyDirectoryFiles(Path.Combine(sourceDirectory, "root"), websiteDirectory, false); const string DATAFILENAME = "data.xml"; // Load style sheets XslCompiledTransform xsltArticle = new XslCompiledTransform(); XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.DtdProcessing = DtdProcessing.Parse; XmlReader reader = XmlReader.Create(Path.Combine(sourceConfigDirectory, "data.xslt"), readerSettings); XsltSettings xsltSettings = new XsltSettings(); xsltSettings.EnableDocumentFunction = true; xsltSettings.EnableScript = true; xsltArticle.Load(reader, xsltSettings, new XmlUrlResolver()); XslCompiledTransform xsltNavigation = new XslCompiledTransform(); xsltNavigation.Load(Path.Combine(sourceConfigDirectory, "navigation.xslt")); string navigationHtml = ""; try { var articles = Directory.EnumerateDirectories(sourcePageDirectory); foreach (string currentDir in articles) { Console.WriteLine("Processing {0}", currentDir); string currentArticle = Path.GetFileName(currentDir); string sourceArticleDirectory = Path.Combine(sourcePageDirectory, currentArticle); string websiteArticleDirectory = Path.Combine(websiteDirectory, "pages", currentArticle); DirectoryInfo di = Directory.CreateDirectory(websiteArticleDirectory); string infilename = Path.Combine(sourceArticleDirectory, DATAFILENAME); int numberOfPages = 1; XmlDocument xmlfile = new XmlDocument(); xmlfile.Load(infilename); numberOfPages = xmlfile.SelectNodes("//page").Count; XsltArgumentList argsListNavigation = new XsltArgumentList(); argsListNavigation.AddParam("selectedArticleName", "", currentArticle); navigationHtml = xsltNavigation.TransformFileToString(Path.Combine(sourceConfigDirectory, "navigation.xml"), argsListNavigation); for (int currentPageno = 1; currentPageno < (numberOfPages + 1); currentPageno++) { string outfilename; outfilename = Path.Combine(websiteArticleDirectory, "page_" + currentPageno.ToString() + ".html"); XsltArgumentList argsListData = new XsltArgumentList(); argsListData.AddParam("selectedPageNo", "", currentPageno.ToString()); argsListData.AddParam("navigationContent", "", navigationHtml); xsltArticle.TransformFileToFile(infilename, argsListData, outfilename); } } } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary>Performs code generation</summary> /// <param name="inputFileName">Name of XSLT template file</param> /// <param name="inputFileContent">Content of XSLT template file</param> /// <returns>File converted</returns> /// <version version="1.5.4">Script and document() function are now enabled in XSL transformations.</version> /// <version version="1.5.4">One more parameter is passed to XSL Template - <c>language</c>.</version> public override string DoGenerateCode(string inputFileName, string inputFileContent) { string xmlFileName = Tools.ResourcesT.TransforCodeGeneratorResources.NOTFOUND; StringWriter outputWriter = new StringWriter(); try { FileInfo inputFileInfo = new FileInfo(inputFileName); // get the XML document for XSLT file XmlDocument XsltDocument = new XmlDocument(); XsltDocument.LoadXml(inputFileContent); // get the filename of xml file var inputPIs = XsltDocument.SelectNodes("/processing-instruction('input')"); if (inputPIs.Count > 0) { xmlFileName = inputPIs[0].Value; } if (!File.Exists(xmlFileName) && !System.IO.Path.IsPathRooted(xmlFileName)) { // try in the same dir as the file xmlFileName = Path.Combine(inputFileInfo.DirectoryName, xmlFileName); if (!File.Exists(xmlFileName)) { // try in the dir where this dll lives FileInfo assemblyFileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location); xmlFileName = Path.Combine(assemblyFileInfo.DirectoryName, xmlFileName); } } // get the xslt document XPathDocument transformerDoc = new XPathDocument(inputFileContent); // get input document XmlDocument inputDocument = new XmlDocument(); inputDocument.Load(xmlFileName); // create the transform XslCompiledTransform xslTransform = new XslCompiledTransform(); var settings = new XsltSettings(true, true); xslTransform.Load(transformerDoc.CreateNavigator(), settings, null); FileInfo fi = new FileInfo(inputFileName); XsltArgumentList args = new XsltArgumentList(); AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName(); args.AddParam("generator", String.Empty, assemblyName.FullName); args.AddParam("version", String.Empty, assemblyName.Version.ToString()); args.AddParam("fullfilename", String.Empty, inputFileName); args.AddParam("filename", String.Empty, fi.Name); args.AddParam("date-created", String.Empty, DateTime.Today.ToLongDateString()); args.AddParam("created-by", String.Empty, String.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName)); args.AddParam("namespace", String.Empty, FileNamespace); args.AddParam("classname", String.Empty, fi.Name.Substring(0, fi.Name.LastIndexOf("."))); args.AddParam("language", string.Empty, CodeProvider.FileExtension); // do the transform xslTransform.Transform(inputDocument, args, outputWriter); XDocument result = XDocument.Parse(outputWriter.ToString()); Tools.CodeDomT.Xml2CodeDom x2d = new Tools.CodeDomT.Xml2CodeDom(); outputWriter = new StringWriter(); base.CodeProvider.GenerateCodeFromCompileUnit(x2d.Xml2CompileUnit(result), outputWriter, new System.CodeDom.Compiler.CodeGeneratorOptions()); } catch (Exception ex) { string bCommentStart; string bCommentEnd; string lCommentStart; if (this.GetDefaultExtension().ToLower() == ".vb") { bCommentStart = "'"; bCommentEnd = "'"; lCommentStart = "'"; } else { bCommentStart = "/*"; bCommentEnd = "*/"; lCommentStart = ""; } outputWriter.WriteLine(bCommentStart); outputWriter.WriteLine(lCommentStart + "\t" + Tools.ResourcesT.TransforCodeGeneratorResources.ERRORUnableToGenerateOutputForTemplate); outputWriter.WriteLine(lCommentStart + "\t'{0}'", xmlFileName); outputWriter.WriteLine(lCommentStart + "\t" + Tools.ResourcesT.TransforCodeGeneratorResources.UsingTransformer); outputWriter.WriteLine(lCommentStart + "\t'{0}'", inputFileName); outputWriter.WriteLine(lCommentStart + ""); outputWriter.WriteLine(lCommentStart + ex.ToString()); outputWriter.WriteLine(bCommentEnd); } return(outputWriter.ToString()); }
/// <summary> /// Loads the RDF Dataset from the TriX input using a RDF Handler /// </summary> /// <param name="handler">RDF Handler to use</param> /// <param name="parameters">Parameters indicating the input to read from</param> public void Load(IRdfHandler handler, IStoreParams parameters) { if (handler == null) { throw new ArgumentNullException("handler", "Cannot parse an RDF Dataset using a null RDF Handler"); } if (parameters == null) { throw new ArgumentNullException("parameters", "Cannot parse an RDF Dataset using null Parameters"); } //Try and get the Input from the parameters TextReader input = null; if (parameters is StreamParams) { //Get Input Stream input = ((StreamParams)parameters).StreamReader; //Issue a Warning if the Encoding of the Stream is not UTF-8 if (!((StreamReader)input).CurrentEncoding.Equals(Encoding.UTF8)) { this.RaiseWarning("Expected Input Stream to be encoded as UTF-8 but got a Stream encoded as " + ((StreamReader)input).CurrentEncoding.EncodingName + " - Please be aware that parsing errors may occur as a result"); } } else if (parameters is TextReaderParams) { input = ((TextReaderParams)parameters).TextReader; } if (input != null) { //First try and load as XML and apply any stylesheets try { XmlDocument doc = new XmlDocument(); doc.Load(input); input.Close(); XmlDocument inputDoc = new XmlDocument(); bool inputReady = false; //If XSL isn't supported we can't apply it #if !NO_XSL //Try and apply any stylesheets (which are used to extend TriX) to get basic TriX syntax foreach (XmlNode child in doc.ChildNodes) { if (child.NodeType == XmlNodeType.ProcessingInstruction) { if (child.Name == "xml-stylesheet") { //Load in the XML a 2nd time so we can transform it properly if needed if (!inputReady) { inputDoc.LoadXml(doc.OuterXml); inputReady = true; } Regex getStylesheetURI = new Regex("href=\"([^\"]+)\""); String stylesheetUri = getStylesheetURI.Match(child.Value).Groups[1].Value; //Load the Transform XslCompiledTransform transform = new XslCompiledTransform(); XsltSettings settings = new XsltSettings(); transform.Load(stylesheetUri, settings, null); //Apply the Transform MemoryStream temp = new MemoryStream(); transform.Transform(inputDoc, XmlWriter.Create(temp)); temp.Flush(); temp.Seek(0, SeekOrigin.Begin); inputDoc.Load(temp); } } } #endif //Start parsing if (!inputReady) { inputDoc = doc; } this.TryParseGraphset(inputDoc, handler); input.Close(); } catch (XmlException xmlEx) { try { input.Close(); } catch { //No catch actions - just cleaning up } //Wrap in a RDF Parse Exception throw new RdfParseException("Unable to Parse this TriX since System.Xml was unable to parse the document into a DOM Tree, see the inner exception for details", xmlEx); } catch { try { input.Close(); } catch { //No catch actions - just cleaning up } throw; } } else { throw new RdfStorageException("Parameters for the TriXParser must be of the type StreamParams/TextReaderParams"); } }
/// <summary> Use the native .NET library to transform a source XML file with the XSLT file and return the string </summary> /// <param name="SourceFile"> Source XML file, to be transformed </param> /// <param name="XSLT_File"> XSLT file to perform the transform </param> /// <returns> XSLT return arguments including a flag for success, and possibly an exception </returns> public static XSLT_Transformer_ReturnArgs Native_Transform(string SourceFile, string XSLT_File) { // Keep track of the start time DateTime starTime = DateTime.Now; // Create the return object XSLT_Transformer_ReturnArgs returnArgs = new XSLT_Transformer_ReturnArgs(); returnArgs.Engine = XSLT_Transformer_Engine_Enum.Native_dotNet; // Ensure the XSLT file exists if (!File.Exists(XSLT_File)) { returnArgs.Successful = false; returnArgs.ErrorMessage = "Indicated XSLT file ( " + XSLT_File + " ) does not exist."; return(returnArgs); } // Ensure the source file exists if (!File.Exists(SourceFile)) { returnArgs.Successful = false; returnArgs.ErrorMessage = "Indicated source file ( " + SourceFile + " ) does not exist."; return(returnArgs); } try { // Create the XsltSettings object with script enabled. XsltSettings xslt_settings = new XsltSettings(true, true); // Create the transform and load the XSL indicated XslCompiledTransform transform = new XslCompiledTransform(); transform.Load(XSLT_File, xslt_settings, new XmlUrlResolver()); // Apply the transform to convert the XML into HTML StringWriter results = new StringWriter(); XmlReaderSettings settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse }; using (XmlReader transformreader = XmlReader.Create(SourceFile, settings)) { transform.Transform(transformreader, null, results); } // Write the transformed string returnArgs.TransformedString = results.ToString(); returnArgs.Successful = true; } catch (Exception ee) { returnArgs.Successful = false; returnArgs.ErrorMessage = ee.Message; returnArgs.InnerException = ee; } // Determine the elapsed time, in milliseconds returnArgs.Milliseconds = DateTime.Now.Subtract(starTime).TotalMilliseconds; return(returnArgs); }
/// <summary> /// This should be a part of the I/O layer /// </summary> public static void LoadFromPath(this XslCompiledTransform xslCompiledTransform, string path, XsltSettings settings, XmlResolver stylesheetResolver) { using (C1StreamReader streamReader = new C1StreamReader(path)) { using (XmlReader xmlReader = XmlReader.Create(streamReader)) { xslCompiledTransform.Load(xmlReader, settings, stylesheetResolver); } } }
/// <summary> /// Compiles the XSLT style sheet contained in the <see cref="IXPathNavigable"/>. /// The <see cref="XmlResolver"/> resolves any XSLT <c>import</c> or <c>include</c> elements and the /// XSLT settings determine the permissions for the style sheet. /// See also <see cref="XslCompiledTransform.Load(IXPathNavigable, XsltSettings, XmlResolver)"/>. /// </summary> /// <param name="stylesheet">An object implementing the <see cref="IXPathNavigable"/> interface. /// In the Microsoft .NET Framework, this can be either an <see cref="XmlNode"/> (typically an <see cref="XmlDocument"/>), /// or an <see cref="XPathDocument"/> containing the style sheet.</param> /// <param name="settings">The <see cref="XsltSettings"/> to apply to the style sheet. /// If this is a null reference (Nothing in Visual Basic), the <see cref="XsltSettings.Default"/> setting is applied.</param> /// <param name="stylesheetResolver">The <see cref="XmlResolver"/> used to resolve any /// style sheets referenced in XSLT <c>import</c> and <c>include</c> elements. If this is a /// null reference (Nothing in Visual Basic), external resources are not resolved.</param> public void Load(IXPathNavigable stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) { this.compiledTransform.Load(stylesheet, settings, stylesheetResolver); }
public override void xslTransformer(XPathNavigator xNav, XsltArgumentList xArgs) { XsltSettings settings = new XsltSettings(true, true); XmlUrlResolver r = new XmlUrlResolver(); r.Credentials = System.Net.CredentialCache.DefaultCredentials; MvpXslTransform xslObj = new MvpXslTransform(); xslObj.SupportCharacterMaps = false; // causes error reading var readersettings = new XmlReaderSettings(); using (XmlReader xslreader = XmlReader.Create(classXSLObjectSource, readersettings)) { xslObj.Load(xslreader, settings, r); XmlInput xm = new XmlInput(xNav); XmlOutput xo; try { if (!(clsFileIO == null)) { xo = new XmlOutput(clsFileIO); xslObj.Transform(xm, xArgs, xo); clsTEXTResult = "FILE SAVED"; } else if (!(clsHTTPResponse == null)) { xo = new XmlOutput(clsHTTPResponse.OutputStream); xslObj.Transform(xm, xArgs, xo); clsTEXTResult = "OUTPUT STREAMED TO HTTP RESPONSE"; } else if (!(clsXMLObjectReturn == null)) { using (StringWriter sWrit = new StringWriter()) { xo = new XmlOutput(sWrit); xslObj.Transform(xm, xArgs, xo); clsXMLObjectReturn.LoadXml(sWrit.ToString()); } } else { using (StringWriter sWrit = new StringWriter()) { xo = new XmlOutput(sWrit); xslObj.Transform(xm, xArgs, xo); // default - results to text clsTEXTResult = sWrit.ToString(); } } } catch (Exception unhandled) { throw unhandled; } finally { xslObj = null; xm = null; xo = null; } } }
static XsltSettings () { defaultSettings = new XsltSettings (true); }
public override bool transform() { // pretreat to the input .uof file of Presentation //preMethod(inputFile); FileStream fs = null; //XmlUrlResolver resourceResolver = null; XmlReader xr = null; string extractPath = Path.GetDirectoryName(outputFile) + Path.AltDirectorySeparatorChar; string prefix = this.GetType().Namespace + "." + TranslatorConstants.RESOURCE_LOCATION + "." + TranslatorConstants.UOFToOOX_POWERPOINT_LOCATION; string uof2ooxpre = extractPath + "uof2ooxpre.xml"; // 调用此部分出异常 所以改为下面语句 string picture_xml = "data"; // string uof2ooxpre = extractPath + "tmpDoc1.xml"; try { // copy XSLT templates Assembly asm = Assembly.GetExecutingAssembly(); foreach (string name in asm.GetManifestResourceNames()) { if (name.StartsWith(prefix)) { string filename = name.Substring(prefix.Length + 1); FileStream writer = new FileStream(extractPath + filename, FileMode.Create); Stream baseStream = asm.GetManifestResourceStream(name); int Length = 10240; Byte[] buffer = new Byte[Length]; int bytesRead = baseStream.Read(buffer, 0, Length); while (bytesRead > 0) { writer.Write(buffer, 0, bytesRead); bytesRead = baseStream.Read(buffer, 0, Length); } baseStream.Close(); writer.Close(); } } //resourceResolver = new ResourceResolver(Assembly.GetExecutingAssembly(), prefix); //xr = XmlReader.Create(((ResourceResolver)resourceResolver).GetInnerStream("uof2oopre.xslt")); xr = XmlReader.Create(extractPath + "uof2ooxpre.xslt"); XPathDocument doc = new XPathDocument(extractPath + @"content.xml"); XslCompiledTransform transFrom = new XslCompiledTransform(); XsltSettings setting = new XsltSettings(true, false); XmlUrlResolver xur = new XmlUrlResolver(); transFrom.Load(xr, setting, xur); XPathNavigator nav = ((IXPathNavigable)doc).CreateNavigator(); // fs = new FileStream(outputFile, FileMode.Create); fs = new FileStream(uof2ooxpre, FileMode.Create); transFrom.Transform(nav, null, fs); fs.Close(); preMethod(uof2ooxpre); //ole对象lyy if (Directory.Exists(extractPath + "drawings") && Directory.Exists(extractPath + "embeddings")) { string tmpOle = extractPath + Path.AltDirectorySeparatorChar + "tmpOle.xml"; XmlDocument xdoc = new XmlDocument(); xdoc.Load(outputFile); XmlNameTable nt = xdoc.NameTable; XmlNamespaceManager nm = new XmlNamespaceManager(nt); nm.AddNamespace("w", TranslatorConstants.XMLNS_W); nm.AddNamespace("uof", TranslatorConstants.XMLNS_UOF); xdoc = OlePretreatment(xdoc, "uof:UOF", extractPath, nm); xdoc.Save(tmpOle); // OutputFilename = tmpPic; outputFile = tmpOle; } if (Directory.Exists(extractPath + picture_xml)) { string tmpPic = extractPath + Path.AltDirectorySeparatorChar + "tmpPic.xml"; XmlDocument xdoc = new XmlDocument(); xdoc.Load(outputFile); XmlNameTable nt = xdoc.NameTable; XmlNamespaceManager nm = new XmlNamespaceManager(nt); nm.AddNamespace("w", TranslatorConstants.XMLNS_W); nm.AddNamespace("uof", TranslatorConstants.XMLNS_UOF); xdoc = PicPretreatment(xdoc, "uof:UOF", extractPath + picture_xml, nm); xdoc.Save(tmpPic); // OutputFilename = tmpPic; outputFile = tmpPic; } //公式 if (File.Exists(extractPath + "equations.xml")) { string tmpEqu = extractPath + Path.AltDirectorySeparatorChar + "tmpEqu.xml"; string equXML = extractPath + "equations.xml"; XmlDocument equDoc = new XmlDocument(); equDoc.Load(equXML); XmlDocument xdoc = new XmlDocument(); xdoc.Load(outputFile); XmlNode equ = xdoc.ImportNode(equDoc.LastChild, true); xdoc.LastChild.AppendChild(equ); xdoc.Save(tmpEqu); outputFile = tmpEqu; } return(true); } catch (Exception ex) { logger.Error("Fail in Uof2.0 to OOX pretreatment1: " + ex.Message); logger.Error(ex.StackTrace); throw new Exception("Fail in Uof2.0 to OOX pretreatment1 of Presentation"); } finally { if (fs != null) { fs.Close(); } } }
/// <summary> /// Performs the transformation. /// </summary> /// <param name="inputPath">The filename of the context item document.</param> /// <param name="xsltPath">The filename of the XSLT transformation.</param> /// <param name="outputPath">The filename of the primary output.</param> private static void PerformTransformation(string inputPath, string xsltPath, string outputPath) { Debug.Assert(inputPath != null, "inputPath in null"); Debug.Assert(xsltPath != null, "xsltPath in null"); Debug.Assert(inputPath != null, "outputPath in null"); // First, we create a new XmlNameTable instance. This will be used to share information such // as element and attribute names between the XML documents and the transformation. var nameTable = new NameTable(); // Next we create an XmlReaderSettings instance and set its NameTable property. // In order for XmlPrime to work correctly all documents passed in to Xslt must be loaded // with the XmlNameTable used to compile the query. var xmlReaderSettings = new XmlReaderSettings { NameTable = nameTable }; // In order to transform the document we load it into an XdmDocument. XdmDocument document; using (var reader = XmlReader.Create(inputPath, xmlReaderSettings)) { document = new XdmDocument(reader); } // In order to describe how the transformation should be compiled we need set up an XsltSettings // object. This describes all the settings used for compilation. // In particular, we will set the name table used by the transformation to match the one we used // earlier and we will set the context item type. // By default the context item type is set to none, and so the context item cannot be set unless // we override the type here. var xsltSettings = new XsltSettings(nameTable) { ContextItemType = XdmType.Node }; // We can then compile the transformation using the Compile method. // This returns us an Xslt object encapsulating the transformation. var xslt = Xslt.Compile(xsltPath, xsltSettings); // Now we have our transformation object we now just need to execute it. // We use a DynamicContextSettings object which describes the parameters used to evaluate the query. // In particular we will set the context item to be the document that we loaded earlier. var contextItem = document.CreateNavigator(); var settings = new DynamicContextSettings { ContextItem = contextItem }; // We will use the ApplyTemplates method to initiate a transformation by applying templates // in the default mode and serializing the primary result document to a stream. using (var outputStream = File.Create(outputPath)) { xslt.ApplyTemplates(settings, outputStream); } // NOTE: We could just have used xslt.ApplyTemplates(contextItem, outputStream) in this simple case. }
/// <summary> /// Compiles the XSLT style sheet contained in the <see cref="IXPathNavigable"/>. /// The <see cref="XmlResolver"/> resolves any XSLT <c>import</c> or <c>include</c> elements and the /// XSLT settings determine the permissions for the style sheet. /// See also <see cref="XslCompiledTransform.Load(IXPathNavigable, XsltSettings, XmlResolver)"/>. /// </summary> /// <param name="stylesheet">An object implementing the <see cref="IXPathNavigable"/> interface. /// In the Microsoft .NET Framework, this can be either an <see cref="XmlNode"/> (typically an <see cref="XmlDocument"/>), /// or an <see cref="XPathDocument"/> containing the style sheet.</param> /// <param name="settings">The <see cref="XsltSettings"/> to apply to the style sheet. /// If this is a null reference (Nothing in Visual Basic), the <see cref="XsltSettings.Default"/> setting is applied.</param> /// <param name="stylesheetResolver">The <see cref="XmlResolver"/> used to resolve any /// style sheets referenced in XSLT <c>import</c> and <c>include</c> elements. If this is a /// null reference (Nothing in Visual Basic), external resources are not resolved.</param> public void Load(IXPathNavigable stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) { LoadStylesheetFromReader(stylesheet.CreateNavigator().ReadSubtree(), settings, stylesheetResolver); }
public static MvcHtmlString RenderXslt(string xslPath, string xmlString, List<KeyValuePair<string, string>> parameters = null) { string xsltResult = string.Empty; try { // XML Settings XmlReaderSettings xmlSettings = new XmlReaderSettings(); xmlSettings.XmlResolver = null; xmlSettings.IgnoreComments = true; xmlSettings.DtdProcessing = DtdProcessing.Ignore; xmlSettings.ValidationType = ValidationType.None; // Attaches an action to the valiation event handler. This will write out error messages in the Output pane. #if DEBUG xmlSettings.ValidationEventHandler += (sender, e) => { Debug.WriteLine(string.Format("{0}({1},{2}): {3} - {4}", e.Exception.SourceUri, e.Exception.LineNumber, e.Exception.LinePosition, e.Severity, e.Message)); }; #endif // XSLT Settings XmlReaderSettings xsltSettings = new XmlReaderSettings(); xsltSettings.XmlResolver = null; xsltSettings.DtdProcessing = DtdProcessing.Ignore; xsltSettings.ValidationType = ValidationType.None; // Attaches an action to the valiation event handler. This will write out error messages in the Output pane. #if DEBUG xsltSettings.ValidationEventHandler += (sender, e) => { Debug.WriteLine(string.Format("{0}({1},{2}): {3} - {4}", e.Exception.SourceUri, e.Exception.LineNumber, e.Exception.LinePosition, e.Severity, e.Message)); }; #endif // Init params XsltArgumentList xslArgs = new XsltArgumentList(); if (parameters != null) { foreach (KeyValuePair<string, string> param in parameters) xslArgs.AddParam(param.Key, string.Empty, param.Value); } // Load XML using (XmlReader reader = XmlReader.Create(new StringReader(xmlString), xmlSettings)) { // Load XSL XsltSettings xslSettings = new XsltSettings(true, true); // Need to enable the document() fucntion using (XmlReader xslSource = XmlReader.Create(xslPath, xsltSettings)) { XslCompiledTransform xsltDoc = new XslCompiledTransform(); xsltDoc.Load(xslSource, xslSettings, new XmlUrlResolver()); // Transform using (var sw = new UTF8StringWriter()) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.OmitXmlDeclaration = true; using (var xw = XmlWriter.Create(sw, settings)) { xsltDoc.Transform(reader, xslArgs, sw); } xsltResult = sw.ToString(); } } } } catch { } // custom error handling here // Return result return MvcHtmlString.Create(xsltResult); }
/// <summary> /// Loads and compiles the XSLT style sheet specified by the URI. /// The <see cref="XmlResolver"/> resolves any XSLT <c>import</c> or <c>include</c> elements and the /// XSLT settings determine the permissions for the style sheet. /// See also <see cref="XslCompiledTransform.Load(string, XsltSettings, XmlResolver)"/>. /// </summary> /// <param name="stylesheetUri">The URI of the style sheet.</param> /// <param name="settings">The <see cref="XsltSettings"/> to apply to the style sheet. /// If this is a null reference (Nothing in Visual Basic), the <see cref="XsltSettings.Default"/> setting is applied.</param> /// <param name="stylesheetResolver">The <see cref="XmlResolver"/> used to resolve any /// style sheets referenced in XSLT <c>import</c> and <c>include</c> elements. If this is a /// null reference (Nothing in Visual Basic), external resources are not resolved.</param> public void Load(string stylesheetUri, XsltSettings settings, XmlResolver stylesheetResolver) { LoadStylesheetFromReader(XmlReader.Create(stylesheetUri), settings, stylesheetResolver); }
public void Load(System.Xml.XmlReader stylesheet, XsltSettings settings, System.Xml.XmlResolver stylesheetResolver) { }
/// <summary> /// Compiles the XSLT style sheet contained in the <see cref="XmlReader"/>. /// The <see cref="XmlResolver"/> resolves any XSLT <c>import</c> or <c>include</c> elements and the /// XSLT settings determine the permissions for the style sheet. /// See also <see cref="XslCompiledTransform.Load(XmlReader, XsltSettings, XmlResolver)"/>. /// </summary> /// <param name="stylesheet">The <see cref="XmlReader"/> containing the style sheet.</param> /// <param name="settings">The <see cref="XsltSettings"/> to apply to the style sheet. /// If this is a null reference (Nothing in Visual Basic), the <see cref="XsltSettings.Default"/> setting is applied.</param> /// <param name="stylesheetResolver">The <see cref="XmlResolver"/> used to resolve any /// style sheets referenced in XSLT <c>import</c> and <c>include</c> elements. If this is a /// null reference (Nothing in Visual Basic), external resources are not resolved.</param> public void Load(XmlReader stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) { LoadStylesheetFromReader(stylesheet, settings, stylesheetResolver); }
public void Load(string stylesheetUri, XsltSettings settings, System.Xml.XmlResolver stylesheetResolver) { }
/// <summary> /// Process Input file with xslt and produce result with same name as input but extension changed. /// </summary> /// <param name="inputFile">input file</param> /// <param name="xsltFile">xslt file name. It is assumed to be in Dictionary Express folder</param> /// <param name="ext">new extension</param> /// <param name="myParams">pass a dictionary of parameters and values</param> /// <returns>results or error message</returns> private static string XsltProcess(string inputFile, string xsltFile, string ext, Dictionary <string, string> myParams) { if (!File.Exists(inputFile)) { return(string.Empty); } if (!File.Exists(xsltFile)) { return(inputFile); } if (string.IsNullOrEmpty(ext)) { ext = ".xhtml"; } try { string path = GetPSApplicationPath(); string outputPath = Path.GetDirectoryName(inputFile); string result = PathCombine(outputPath, Path.GetFileNameWithoutExtension(inputFile) + ext); if (File.Exists(result)) { File.Delete(result); } string xsltPath = PathCombine(path, xsltFile); if (!File.Exists(xsltPath)) { xsltPath = Common.PathCombine(Path.GetDirectoryName(Common.AssemblyPath), xsltFile); } //Create the XslCompiledTransform and load the stylesheet. var xsltReader = XmlReader.Create(xsltPath); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xsltReader.NameTable); namespaceManager.AddNamespace("x", "http://www.w3.org/1999/xhtml"); namespaceManager.AddNamespace("fn", "http://www.w3.org/2005/xpath-functions"); var xslt = new XslCompiledTransform(); var xsltTransformSettings = new XsltSettings { EnableDocumentFunction = true }; xslt.Load(xsltReader, xsltTransformSettings, null); xsltReader.Close(); //Create an XsltArgumentList. var xslArg = new XsltArgumentList(); if (myParams != null) { foreach (string param in myParams.Keys) { xslArg.AddParam(param, "", myParams[param]); } } //Transform the file. and writing to temporary File var setting = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse, XmlResolver = null }; XmlReader reader = XmlReader.Create(inputFile, setting); var writerSettings = new XmlWriterSettings(); if (!IncludeUtf8BomIdentifier || !ext.ToLower().Contains("xhtml")) { writerSettings.ConformanceLevel = ConformanceLevel.Fragment; } if (IncludeUtf8BomIdentifier) { writerSettings.Encoding = Encoding.UTF8; } else { writerSettings.Encoding = new UTF8Encoding(IncludeUtf8BomIdentifier); IncludeUtf8BomIdentifier = true; // reset to true for next time if it has been changed } if (XsltFormat == Formatting.Indented) { writerSettings.Indent = true; XsltFormat = Formatting.None; // reset to None for next time if it has been changed } var writer = XmlWriter.Create(result, writerSettings); if (ext.ToLower().Contains("xhtml")) { writer.WriteStartDocument(); } xslt.Transform(reader, xslArg, writer); writer.Close(); reader.Close(); return(result); } catch (FileNotFoundException ex) { return(ex.Message); } catch (Exception ex) { MessageBox.Show(ex.Message); return(ex.Message); } }