Reputation: 161
I am Working on Visual-studio 2012 in C#. I want to get the names of total number of templates in a given xslt(Template.xslt) file. Given below code gives only the first template.
List<string> listTemplates = new List<string>();
XmlDocument xslDoc = new XmlDocument();
xslDoc.Load("Template.xslt");
XmlNamespaceManager nsMgr = new XmlNamespaceManager(xslDoc.NameTable);
nsMgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
XmlAttribute valueOf = (XmlAttribute)xslDoc.SelectSingleNode("/xsl:stylesheet/xsl:template/@name", nsMgr);
Let me know how i get all the template names from an XSLT file.
Upvotes: 1
Views: 1021
Reputation: 161
After having template names, I want to read its param names. For a particular template I wrote the below code(templateName is the name of the Template in the XSLT file):
XmlNodeList templateParam = (XmlNodeList)xslDoc.SelectNodes("/xsl:stylesheet/xsl:template/[@name = '" + templateName + "']/xsl:param/@name", nsMgr);
It shows an error "Expression must evaluate to a node-set." What am i missing here?
Upvotes: 0
Reputation: 11085
You can use the below method which uses System.Linq.XElement.
public static IEnumerable<string> GetTemplateNames(string xsltPath)
{
var xsl = XElement.Load(xsltPath);
return xsl.Elements("{http://www.w3.org/1999/XSL/Transform}template")
.Where(temp => temp.Attribute("name") != null)
.Select(temp => temp.Attribute("name").Value);
}
Alternatively, you can do a slight modification in your code to achieve the same.
List<string> listTemplates = new List<string>();
XmlDocument xslDoc = new XmlDocument();
xslDoc.Load("Template.xslt");
XmlNamespaceManager nsMgr = new XmlNamespaceManager(xslDoc.NameTable);
nsMgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
var nameAttributes = xslDoc
.SelectNodes("/xsl:stylesheet/xsl:template/@name", nsMgr)
.Cast<XmlAttribute>();
var names=nameAttributes.Select(n => n.Value);
Upvotes: 1