'C# XSLT transformer uses self closing HTML tags which are invalid
Using C#, I want to transform an xml string to an html string with xslt. However, some tags are transformed as self closing. Actually, this is a duplicate of XSLT self-closing tags issue and Prevent XslCompiledTransform from using self-closing tags . Unfortunately, could not make it work with the answers given to them. Below is a minimal fiddle.
https://dotnetfiddle.net/zsqent
Current output is
<div>
<div class="test" />
<i class="test" />
</div>
whereas I need it to be
<div>
<div class="test"></div>
<i class="test"></i>
</div>
In case fiddle gets deleted, here is a copy of it
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Xsl;
public class Program
{
public static void Main()
{
var xml = @"<a href=""#"" target=""_blank"">Click here</a>";
var xsl = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">
<xsl:strip-space elements=""*"" />
<xsl:template match=""/"">
<div>
<div class=""test""></div>
<i class=""test""></i>
</div>
</xsl:template>
</xsl:stylesheet>";
var html = TransformXml(xml, xsl);
Console.WriteLine(html);
}
public static string TransformXml(string xml, string xslt)
{
var transformedDocument = new XDocument();
using (var xsltStringReader = new StringReader(xslt))
{
var xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.DtdProcessing = DtdProcessing.Parse;
using (XmlReader xsltReader = XmlReader.Create(xsltStringReader, xmlReaderSettings))
{
var transformer = new XslCompiledTransform();
transformer.Load(xsltReader);
using (var xmlStringReader = new StringReader(xml))
{
using (XmlReader xmlReader = XmlReader.Create(xmlStringReader, xmlReaderSettings))
{
using (XmlWriter newDocumentWriter = transformedDocument.CreateWriter())
{
transformer.Transform(xmlReader, newDocumentWriter);
}
}
}
}
}
return transformedDocument.ToString();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
