How to transform XML to HTML with XSLT in C#?

前端 未结 1 1004
无人及你
无人及你 2021-01-16 07:41

How can I transform XML to HTML with XSLT in ASP.NET Core?

I thought about:

public static string TransformXMLToHTML(string inputXml, string xsltStr         


        
相关标签:
1条回答
  • 2021-01-16 08:41

    The System.Xml.Xsl disappeared in .NET Core 1.0 as XSD (XmlSchema) or XSLT (XslTransform) is not supported in .NET Standard 1.0, which .NET Core implements until version '.NET Core 2.0'. Good news are that since .NET Core 2.0 it implements .NET Standard 2.0, so we have System.Xml.Xsl again.

    If you are confused with all of these standards, frameworks and platforms, watch the video in this post .NET Standard 2.0 is out and it’s impressive!!!! and see the .NET Standard Versions table to understand what platforms implement what .NET standards and what is supported in each new version.

    So to answer your question, you need to upgrade your .NET Core app to .NET Core 2.0 and your code will work again.

    public static string TransformXMLToHTML(string inputXml, string xsltString)
    {
        XslCompiledTransform transform = new XslCompiledTransform();
        using(XmlReader reader = XmlReader.Create(new StringReader(xsltString))) {
            transform.Load(reader);
        }
        StringWriter results = new StringWriter();
        using(XmlReader reader = XmlReader.Create(new StringReader(inputXml))) {
            transform.Transform(reader, null, results);
        }
        return results.ToString();
    }
    

    If you need to return XDocument you can the code below, which is similar to your but return instance of 'XML' document:

    public XDocument Transform(string xml, string xsl)
    {
        var originalXml = XDocument.Load(new StringReader(xml));
    
        var transformedXml = new XDocument();
        using (var xmlWriter = transformedXml.CreateWriter())
        {
            var xslt = new XslCompiledTransform();
            xslt.Load(XmlReader.Create(new StringReader(xsl)));
    
            // Add XSLT parameters if you need
            XsltArgumentList xsltArguments = null; // new XsltArgumentList();
            // xsltArguments.AddParam(name, namespaceUri, parameter);
    
            xslt.Transform(originalXml.CreateReader(), xsltArguments, xmlWriter);
        }
    
        return transformedXml;
    }
    
    0 讨论(0)
提交回复
热议问题