tags:

views:

106

answers:

2

In my web application, I display the search results using XSLT. There are some hard coded text in XSLT file which I want to make 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>

Is it possible to pick the text "There are no blog posts to display." from a resource file?

+5  A: 

I'm assuming that by "resource file" you mean a regular resx that is compiled into the assembly. In which case, not directly from xslt; however, you could add an extension object and use a key-base approach, i.e.

<xsl:value-of select="resx:getString('noposts')"/>

The "resx" alias would be mapped (xmlns) to a uri that you use when creating your xslt wrapper in C#. For example, with the xmlns (in the xslt preamble):

xmlns:resx="myextnuri"

we can map that 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 to inject managed code (as extensions) into our xslt.

Marc Gravell
Great help. It worked!Thanks!
Vijay
`msxsl:script` is yet another option.
Pavel Minaev
I can't see how `msxsl:script` would provide access to resx; I'd love to see an example...
Marc Gravell
+2  A: 

You can load resources from an external file using the document() function:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
    <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>
0xA3