Implementing XSLT
In my web application, I am displaying search results using XSLT. There is some hard-coded text in the XSLT file that I want to make it language independent.
XSLT:
<xsl:if test="$IsEmpty">
<table cellpadding="5" cellspacing="0" border="1" style="width:100%;border-top-style:solid;border-bottom-style:solid;border-left-style:solid;border-right-style:solid;border-top-color:gray;border-bottom-color:gray;border-left-color:gray;border-right-color:gray;border-top-width:1px;border-bottom-width:1px;border-left-width:1px;border-right-width:1px;">
<tr>
<td style="text-align:center;">
There are no blog posts to display.
</td>
</tr>
</table>
</xsl:if>
Can I select text "There are no blog posts to display."
from a resource file?
source to share
I am assuming that by "resource file" you mean a normal resx that is compiled into an assembly. In this case, not directly from the xslt; however you can add an extension object and use the keybase approach, i.e.
<xsl:value-of select="resx:getString('noposts')"/>
The alias "resx" will map ( xmlns
) to the uri you are using when you create the xslt wrapper in C #. For example, with xmlns
(in the xslt preamble):
xmlns:resx="myextnuri"
we can display this in C # via:
public class MyXsltExtension {
public string getString(string key) {
return "TODO: Read from resx: " + key;
}
}
and attach this to the namespace:
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("xslt.xslt");
XsltArgumentList args = new XsltArgumentList();
object obj = new MyXsltExtension();
args.AddExtensionObject("myextnuri", obj);
using (XmlWriter writer = XmlWriter.Create("out.xml")) {
xslt.Transform("xml.xml", args, writer);
}
We now have full control over injecting managed code (as extensions) into our xslt.
source to share
You can load resources from an external file using the function document()
:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes"/>
<xsl:template match="@* | node()">
<html>
<head>
<title>Test</title>
</head>
<body>
<p>
<xsl:value-of select="document('resources.xml')/items/item[@id = 'no_posts']"/>
</p>
</body>
</html>
</xsl:template>
XML resource file:
<?xml version="1.0" encoding="utf-8"?>
<items>
<item id="no_posts">There are no blog posts to display.</item>
</items>
</xsl:stylesheet>
source to share