Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with ampersand in XSLT output

Tags:

c#

.net

xslt

I use XSL to transform a XML document into HTML in .NET.

One of the nodes in the XML has a URL that should be output as the href parameter of the a HTML tag of the HTML. When the input URL has an ampersand character (e.g. http://servers/path?par1=val1&par2=val2) the ampersand appears in the output HTML as &.

Is there any way to solve this issue? Is disable-output-escaping the solution? Would not that create a whole bunch of other problems?

Here's a code sample that reproduces the issue and its output:

Output:

<html>
  <body>
    <a href="http://servers/path?par1=val1&amp;par2=val2#section1" />
  </body>
</html>

C# Code:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Xml;
using System.Xml.Xsl;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {   
            XmlDocument xmlDoc = ComposeXml();
            XmlDocument styleSheet = new XmlDocument();
            styleSheet.LoadXml(XslStyleSheet);

            XmlTextWriter myWriter = new XmlTextWriter(Console.Out);
            myWriter.Formatting = Formatting.Indented;

            XslCompiledTransform myXslTrans = new XslCompiledTransform();
            myXslTrans.Load(styleSheet);
            myXslTrans.Transform(xmlDoc, null, myWriter);

            Console.ReadKey();
        }

        private const string XslStyleSheet =
@"<xsl:stylesheet version=""1.0""
xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">

<xsl:template match=""/"">
  <html>
  <body>
    <a>
        <xsl:attribute name=""href"">
            <xsl:value-of select=""root/url"" />
        </xsl:attribute>      
    </a>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet>";

        static private XmlDocument ComposeXml()
        {
            XmlDocument doc = new XmlDocument();
            XmlElement rootNode = doc.CreateElement("root");
            doc.AppendChild(rootNode);

            XmlElement urlNode = doc.CreateElement("url");
            urlNode.InnerText = "http://servers/path?par1=val1&par2=val2#section1";

            rootNode.AppendChild(urlNode);

            return doc;

        }
    }
}
like image 229
David Reis Avatar asked Mar 01 '23 03:03

David Reis


1 Answers

The output that you get is acceptable HTML.
As I just learned from here, that's actualy THE correct way to write an URL inside an HTML page!
So I think there should be a way of generating the character by itself but you probably don't need to (shouldn't).

like image 188
pauloya Avatar answered Mar 08 '23 05:03

pauloya