I have an xml being returned by an extension method. Can some please help me to use <xsl:for-each> on this xml.
public class CustomObj
{
//function that gets called from XSLT
public XPathNodeIterator GetResultTable()
{
DataTable table = new DataTable("Table1");
table.Columns.Add("SourceCity");
table.Columns.Add("DestinationCity");
table.Columns.Add("Fare");
table.Rows.Add(new object[] { "New York", "Las Vegas", "100" });
table.Rows.Add(new object[] { "New York", "London", "200" });
table.Rows.Add(new object[] { "New York", "New Delhi", "250" });
StringWriter writer = new StringWriter();
table.WriteXml(writer);
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Root");
root.InnerXml = writer.ToString();
doc.AppendChild(root);
return doc.CreateNavigator().Select("root");
}
}
I want to iterate over this xml. Some one please help. I am new to XSLT and would appreciate if you can provide example on the given xml itself.
There are two things to note:
It is much more natural to apply the transformation to the result of invoking the method
GetResultTable()than to get its result via an extension function.As written the
GetResultTable()method doesn’t return any node at all: in the statement—
the
Select()method doesn’t select anything as there is norootelement indoc. The element namedRootisn’t selected, because XML and XPath are case-sensitive.Another observation is that it isn’t necessary at all to use
xsl:for-eachwithin an XSLT transformation — this is considered not a good practice in most cases.Having said that, here is the complete code for what this question asks for:
and the file
My.xslt:When the application is executed, the wanted, correct result is produced: