简体   繁体   中英

Read template names of an XSLT using C# code

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.

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);

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM