How to apply an XSLT Stylesheet in C#

前端 未结 4 1658
无人及你
无人及你 2020-11-22 07:53

I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File.

4条回答
  •  情深已故
    2020-11-22 08:30

    This might help you

    public static string TransformDocument(string doc, string stylesheetPath)
    {
        Func GetXmlDocument = (xmlContent) =>
         {
             XmlDocument xmlDocument = new XmlDocument();
             xmlDocument.LoadXml(xmlContent);
             return xmlDocument;
         };
    
        try
        {
            var document = GetXmlDocument(doc);
            var style = GetXmlDocument(File.ReadAllText(stylesheetPath));
    
            System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
            transform.Load(style); // compiled stylesheet
            System.IO.StringWriter writer = new System.IO.StringWriter();
            XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
            transform.Transform(xmlReadB, null, writer);
            return writer.ToString();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    
    }   
    

提交回复
热议问题