Problem with ampersand in XSLT output
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 charac开发者_运维百科ter (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&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;
}
}
}
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).
When you try to write XML as an attribute value, it's always encoded. But, for text nodes, you can disable that encoding by using disable-output-escaping
attribute:
<a href="{root/url}">
<xsl:value-of select="root/url" disable-output-escaping="yes" />
</a>
精彩评论