This document already has a 'DocumentElement' node -Exception - c#

I get this Exception when in try to convert data relation from Data set tables to xml to make an XmlDataSource supply it to Dynamic Menu Control.
This is the Code behind
DataSet ds = new DataSet();
SqlCommand cmdmenu = new SqlCommand("select CategoryID,CategoryName from Category ", ConManager.Con());
SqlCommand com2 = new SqlCommand("select CategoryIDToSub,subcategoryid ,SubCategoryName from CategorySub", ConManager.Con());
SqlCommand cmd3 = new SqlCommand("select subcategoryid 'SubCategoryID2',Sub2CategoryName from CategorySub2", ConManager.Con());
SqlDataAdapter menadapter = new SqlDataAdapter(cmdmenu.CommandText, ConManager.Con());
SqlDataAdapter menadapter2 = new SqlDataAdapter(com2.CommandText, ConManager.Con());
SqlDataAdapter menadapter3 = new SqlDataAdapter(cmd3.CommandText, ConManager.Con());
menadapter.Fill(ds, "Menu");
menadapter.SelectCommand = com2;
menadapter2.Fill(ds, "SubMenu");
menadapter3.SelectCommand = cmd3;
menadapter3.Fill(ds, "SubSubMenu");
DataColumn colParent =
ds.Tables["Menu"].Columns["CategoryID"];
DataColumn colChild =
ds.Tables["SubMenu"].Columns["CategoryIDToSub"];
DataRelation relation = new DataRelation("relationName",
colParent,
colChild, true);
DataRelation Relation2 = new DataRelation("relationName2",
ds.Tables["SubMenu"].Columns["subcategoryid"],
ds.Tables["SubSubMenu"].Columns["SubCategoryID2"], true);
relation.Nested = true;
Relation2.Nested = true;
ds.Relations.Add(relation);
ds.Relations.Add(Relation2);
XmlDataSource.Data = ds.GetXml();
if (Request.Params["Sel"] != null)
Page.Controls.Add(new System.Web.UI.LiteralControl("You selected " + Request.Params["Sel"]));
and this is the Xslt File Code
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="utf-8"/>
<!-- Replace root node name Menus with MenuItems
and call MenuListing for its children-->
<xsl:template match="/Menus">
<MenuItems>
<xsl:call-template name="MenuListing" />
</MenuItems>
</xsl:template>
<!-- Allow for recursive child nodeprocessing -->
<xsl:template name="MenuListing">
<xsl:apply-templates select="Menu" />
</xsl:template>
<xsl:template match="Menu">
<MenuItem>
<!-- Convert Menu child elements to MenuItem attributes -->
<xsl:attribute name="Text">
<xsl:value-of select="CategoryName"/>
</xsl:attribute>
<xsl:attribute name="ToolTip">
<xsl:value-of select="Remarks"/>
</xsl:attribute>
<xsl:attribute name="NavigateUrl">
<xsl:text>?Sel=</xsl:text>
<xsl:value-of select="Text"/>
</xsl:attribute>
<xsl:attribute name="Text2">
<xsl:value-of select="SubCategoryName"/>
</xsl:attribute>
<xsl:attribute name="Test3">
<xsl:value-of select="Sub2CategoryName3"/>
</xsl:attribute>
<!-- Recursively call MenuListing forchild menu nodes -->
<xsl:if test="count(Menu) >0">
<xsl:call-template name="MenuListing" />
</xsl:if>
</MenuItem>
</xsl:template>
</xsl:stylesheet>
and this is the Menu Control and the XmlDataSource Code
<asp:Menu ID="Menu" runat="server" BackColor="#E3EAEB" DynamicHorizontalOffset="2" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#666666" StaticSubMenuIndent="10px" DataSourceID="XmlDataSource" Width="225px" onmenuitemclick="Menu_MenuItemClick">
<DataBindings>
<asp:MenuItemBinding DataMember="MenuItem" NavigateUrlField="NavigateUrl" TextField="Text" />
<asp:MenuItemBinding DataMember="MenuItem" NavigateUrlField="NavigateUrl" TextField="Text2" />
<asp:MenuItemBinding DataMember="MenuItem" NavigateUrlField="NavigateUrl" TextField="Text3" />
</DataBindings>
<StaticSelectedStyle BackColor="#1C5E55" />
<StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
<DynamicHoverStyle BackColor="#666666" ForeColor="White" />
<DynamicMenuStyle BackColor="#E3EAEB" />
<DynamicSelectedStyle BackColor="#1C5E55" />
<DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
<StaticHoverStyle BackColor="#666666" ForeColor="White" />
</asp:Menu>
<asp:XmlDataSource ID="XmlDataSource" runat="server"
TransformFile="~/TransformXSLT.xsl" XPath="MenuItems/MenuItem">
</asp:XmlDataSource>

Your XML document is not well formed. You have more than one document (root) element. For example:
<a>some</a>
<a>thing</a>
is not well formed. Whereas:
<list>
<a>some</a>
<a>thing</a>
</list>
is well formed.

Related

XSLT in a loop keep getting only first file transformation in the output. How to Stop caching XSLT output

When I am looping thru list of files and doing transformation on each file in a folder the effect of the transformation is as if it keeps transforming first file again and again. The transformation looked to be caching.
Here is the Code for transformation:
I am doing this inside WebAPI call.. in .NET framework 4.5.2 version . The ASP.NET page is calling the WebAPI.
I tried all different overloads and moving instancing transformation new out of loop on the top. I did not find any easy way of disabling the caching.
var d = new DirectoryInfo(strXMLFolder);
foreach (FileInfo file in d.GetFiles())
{
String strXSLTFile = strParamArr[2];
String xmlFile = file.Name;
//File.WriteAllBytes(strFile, transferObj.XSLTTemplateFileData);
XslCompiledTransform proc = new XslCompiledTransform();
proc.Load(strXSLTFolder + strXSLTFile);
proc.Transform(strXMLFolder + xmlFile, strXMLFolder + xmlFile + "-IntermediateXML.xml");
..................................
The XSLT file has following Code:
<data>
<xsl:for-each select="//QuantitativeResponseAssay/Setup/Elements/*/Name">
<row>
<PLA_file_name>
<xsl:value-of select="$vFileName"/>
</PLA_file_name>
<Analyst>
<xsl:value-of select="$vAnalyst"/>
</Analyst>
<xsl:choose>
<xsl:when test="position() = 1">
<Sample>Reference</Sample>
</xsl:when>
<xsl:when test="position() = 2">
<Sample>Sample 1</Sample>
</xsl:when>
<xsl:when test="position() = 3">
<Sample>Sample 2</Sample>
</xsl:when>
<xsl:when test="position() = 4">
<Sample>QC</Sample>
</xsl:when>
<xsl:otherwise>
<Sample>Error</Sample>
</xsl:otherwise>
</xsl:choose>
<Sample_Name>
<xsl:value-of select="."/>
</Sample_Name>
<Upper_Asymptote>
<xsl:value-of select="//StatisticTestResults/StatisticTestResult[TestName='AdditionalTestParameterEstimateUpperAsymptote'][./InvolvedAssayElements[Name=current()]]/Value"/>
</Upper_Asymptote>
<Dynamic_Range>
<xsl:value-of select="//StatisticTestResult[TestName='AdditionalTestParameterEstimateDynamicRange'][./InvolvedAssayElements[Name=current()]]/Value" />
</Dynamic_Range>
<Slope_Factor>
<xsl:value-of select="//StatisticTestResult[TestName='AdditionalTestParameterEstimateSlope'][./InvolvedAssayElements[Name=current()]]/Value"/>
</Slope_Factor>
<Regression_pvalue>
<xsl:if test="current() != 'Reference Standard'">
<xsl:value-of select="//QuantitativeResponseAssay/AssayResults/AssayResult/StatisticTestResults/StatisticTestResult[TestName='FTestRegression'][./InvolvedAssayElements[Name=current()]]/PValue" />
</xsl:if>
</Regression_pvalue>
<nonparallelism_pvalue>
<xsl:if test="current() != 'Reference Standard'">
<xsl:value-of select="//QuantitativeResponseAssay/AssayResults/AssayResult/StatisticTestResults/StatisticTestResult[TestName='FTestNonParallelism'][./InvolvedAssayElements[Name=current()]]/PValue" />
</xsl:if>
</nonparallelism_pvalue>
<LOF_pvalue>
<xsl:if test="current() != 'Reference Standard'">
<xsl:value-of select="//QuantitativeResponseAssay/AssayResults/AssayResult/StatisticTestResults/StatisticTestResult[TestName='FTestNonLinearity'][./InvolvedAssayElements[Name=current()]]/PValue" />
</xsl:if>
</LOF_pvalue>
<Potency>
<xsl:if test="string-length(//QuantitativeResponseAssay/AssayResults/AssayResult/PotencyResults/PotencyResult[TestControlSampleName=current()]/RelativePotencyValue) > 1">
<xsl:value-of select="//QuantitativeResponseAssay/AssayResults/AssayResult/PotencyResults/PotencyResult[TestControlSampleName=current()]/RelativePotencyValue * 100 " />
</xsl:if>
</Potency>
<!-- Column L Width_CI v -->
<Width_CI>
<xsl:if test="string-length(//QuantitativeResponseAssay/AssayResults/AssayResult/PotencyResults/PotencyResult[TestControlSampleName=current()]/PercentualRelativePotencyRange) > 1">
<xsl:value-of select="//QuantitativeResponseAssay/AssayResults/AssayResult/PotencyResults/PotencyResult[TestControlSampleName=current()]/PercentualRelativePotencyRange * 100 " />
</xsl:if>
</Width_CI>
<!-- Column M A_unrestricted v -->
<A_unrestricted>
<xsl:value-of select="//FullModel/FitResult/ParameterEstimate[ParameterName='A'][AssayElementName=current()]/Value" />
</A_unrestricted>
<!-- Column N B_unrestricted v -->
<B_unrestricted>
<xsl:value-of select="//FullModel/FitResult/ParameterEstimate[ParameterName='B'][AssayElementName=current()]/Value" />
</B_unrestricted>
<!-- Column O C_log2_unrestricted v -->
<C_unrestricted>
<xsl:value-of select="//FullModel/FitResult/ParameterEstimate[ParameterName='C'][AssayElementName=current()]/Value"/>
</C_unrestricted>
<!-- Column P D_unrestricted v -->
<D_unrestricted>
<xsl:value-of select="//FullModel/FitResult/ParameterEstimate[ParameterName='D'][AssayElementName=current()]/Value" />
</D_unrestricted>
<!-- Column Q G_unrestricted v -->
<G_unrestricted>
<xsl:value-of select="//FullModel/FitResult/ParameterEstimate[ParameterName='G'][AssayElementName=current()]/Value" />
</G_unrestricted>
<Template_ID>
<xsl:value-of select="$vTemplate"/>
</Template_ID>
<Template_Revision>
<xsl:value-of select="$vTemplateRevision"/>
</Template_Revision>
</row>
</xsl:for-each>
</data>
I expect different output in each intermediate.XML file but I keep getting the fist file result in the output in intermediate file.

c# XDocument : Check if particular node name exists , if not add

I have below node which needs to be added in xslt if not exists :-
<xsl:template name="URLSpliter">
<xsl:param name="url" />
<xsl:variable name="splitURL" select="substring-after($url, '/')" />
<xsl:if test="contains($splitURL, '/')">
<!--To call the template recursively-->
<xsl:call-template name="URLSpliter">
<xsl:with-param name="url" select="$splitURL" />
</xsl:call-template>
</xsl:if>
<xsl:if test="not(contains($splitURL, '/'))">
<xsl:value-of select="$splitURL" />
</xsl:if>
</xsl:template>
For this, first I need to check if it exists or not ?-
I have checked it through -
IEnumerable<XElement> xElements = from xmlAuthor in doc.Descendants()
let xElement = xmlAuthor.Element("URLSpliter")
where xElement != null
select xmlAuthor;
var IsUrlSplitterExists= xElements.Any();
if(IsUrlSplitterExists)
{
}
1.I want to know if its correct way or not?
If not exists (element [name="URLSpliter"]) then needs to add.
How can I add it as a first node of xslt?
To select such elements in the XSLT namespace with LINQ to XML you would use
XNamespace xsl = "http://www.w3.org/1999/XSL/Transform";
if (!doc.Root.Elements(xsl + "template").Where(t => (string)t.Attribute("name") == "URLSplitter").Any()) {
doc.Root.AddFirst(new XElement(xsl + "template", new XAttribute("name", "URLSplitter"), ...))
}
Of course, as XSLT is XML, you might as well use XSLT to manipulate your XSLT:
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:axsl="http://www.w3.org/1999/XSL/Transform-alias"
exclude-result-prefixes="axsl"
version="1.0">
<xsl:namespace-alias stylesheet-prefix="axsl" result-prefix="xsl"/>
<xsl:output indent="yes"/>
<xsl:param name="new-template">
<axsl:template name="URLSpliter">
<axsl:param name="url" />
<axsl:variable name="splitURL" select="substring-after($url, '/')" />
<axsl:if test="contains($splitURL, '/')">
<!--To call the template recursively-->
<axsl:call-template name="URLSpliter">
<axsl:with-param name="url" select="$splitURL" />
</axsl:call-template>
</axsl:if>
<axsl:if test="not(contains($splitURL, '/'))">
<axsl:value-of select="$splitURL" />
</axsl:if>
</axsl:template>
</xsl:param>
<xsl:template match="#* | node()">
<xsl:copy>
<xsl:apply-templates select="#* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="xsl:transform[not(xsl:template[#name = 'URLSplitter'])] | xsl:stylesheet[not(xsl:template[#name = 'URLSplitter'])]">
<xsl:copy>
<xsl:apply-templates select="#*"/>
<xsl:copy-of select="$new-template"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
https://xsltfiddle.liberty-development.net/94rmq5T

ASP.NET: gridview sorting using XSLT not working

I am quite new to XML-XSLT coding.
I am binding XmlDataSource to my gridview by using XSLT. I want to sort the column upon clicking on the header. I do not want to convert xml to dataset and bind to gridview to achieve sorting. Here is my code:
<asp:XmlDataSource ID="XmlDataSource1" runat="server"></asp:XmlDataSource>
<asp:GridView ID="gvResult" runat="server" HorizontalAlign="Center" AutoGenerateColumns="false" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" AllowPaging="True"
OnPageIndexChanging="gvResult_PageIndexChanging" AllowSorting="true" OnSorting="gvResult_Sorting">
<Columns>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<asp:HyperLink runat="server" NavigateUrl='~/NewForm.aspx?ID=<%# XPath("#ID") %>'>
<%# XPath("#ID") %>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="employee_number" HeaderText="Employee Number" SortExpression="last_name"/>
<asp:BoundField DataField="name" HeaderText="Employee Name" SortExpression="last_name" />
<asp:BoundField DataField="date_joining" HeaderText="Joining Date" SortExpression="date_joining" />
<asp:BoundField DataField="date_paid" HeaderText="Date Paid" SortExpression="last_name"/>
<asp:BoundField DataField="amount" HeaderText="Salary" />
<asp:BoundField DataField="status" HeaderText="Status" />
</Columns>
</asp:GridView>
protected void gvResult_Sorting(object sender, GridViewSortEventArgs e)
{
XsltArgumentList xslTrnsform = new XsltArgumentList();
switch (e.SortExpression)
{
case "employee_number":
xslTrnsform.AddParam("sortby", "", "employee_number");
xslTrnsform.AddParam("order", "", "ascending");
//xslTrnsform.AddParam("datatype", "", "number");
break;
case "date_joining":
xslTrnsform.AddParam("sortby", "", "#date_joining");
xslTrnsform.AddParam("order", "", "ascending");
//xslTrnsform.AddParam("data-type", "", "text");
break;
case "date_paid":
xslTrnsform.AddParam("sortby", "", "#date_paid");
xslTrnsform.AddParam("order", "", "ascending");
//xslTrnsform.AddParam("data-type", "", "text");
break;
}
XmlDataSource1.EnableCaching = false;
XmlDataSource1.Data = ResponseObj.OuterXml;
XmlDataSource1.TransformArgumentList = xslTrnsform;
XmlDataSource1.TransformFile = "employees.xslt";
XmlDataSource1.XPath = "/employees/employee"; ;
// Bind the DataSet to the grid view
gvResult.DataSource = XmlDataSource1;
gvResult.DataBind();
gvResult.Visible = true;
}
<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:param name="sortby" select="#employee_number"/>
<xsl:param name="order" select="'ascending'"/>
<xsl:template match="employees">
<employees>
<xsl:apply-templates select="employee">
<xsl:sort select="*[name()=$sortby]" order="{$order}" />
</xsl:apply-templates>
</employees>
</xsl:template>
<xsl:template match="employee">
<employee>
<xsl:attribute name="ID">
<xsl:value-of select="#ID"/>
</xsl:attribute>
<xsl:attribute name="employee_number">
<xsl:value-of select="#employee_number"/>
</xsl:attribute>
<xsl:attribute name="name">
<xsl:value-of select="#last_name"/>, <xsl:value-of select="#first_name"/>
</xsl:attribute>
<xsl:attribute name="date_joining">
<xsl:value-of select="#date_joining" />
</xsl:attribute>
<xsl:attribute name="dte_to_date">
<xsl:value-of select="#dte_to_date" />
</xsl:attribute>
<xsl:attribute name="date_paid">
<xsl:value-of select="#date_paid"/>
</xsl:attribute>
<xsl:attribute name="date_paid">
<xsl:value-of select="#date_paid"/>
</xsl:attribute>
<xsl:attribute name="amount">
<xsl:value-of select="#amount"/>
</xsl:attribute>
<xsl:attribute name="status">
<xsl:value-of select="#status"/>
</xsl:attribute>
</employee>
</xsl:template>
</xsl:stylesheet>
Data is displayed on the gridview. But when I click on header, nothing happens. Also I have to apply sorting for "name" column, which consists of lastname,firstname.
One problem you have is you are inconsistent about how you are setting the sortby parameters. In one place you do this...
xslTrnsform.AddParam("sortby", "", "employee_number");
But in another place you do this...
xslTrnsform.AddParam("sortby", "", "#date_joining");
As it looks like all your data is held in attributes, for the sake of consistency, it might be easier to drop the # prefix in all cases. Then, your xsl:sort can look like this
<xsl:sort select="#*[name()=$sortby]" order="{$order}" />
(Previously you were doing select="*[name()=$sortby] which would look for elements not attributes.)
To get your name column to sort by last_name and first_name you could add a second sorting parameter
case "name":
xslTrnsform.AddParam("sortby", "", "last_name");
xslTrnsform.AddParam("sortbysecond", "", "first_name");
xslTrnsform.AddParam("order", "", "ascending");
break;
Then, assuming you declare the sortbysecond parameter in your XSLT, your sort would look like this
<xsl:apply-templates select="employee">
<xsl:sort select="#*[name()=$sortby]" order="{$order}" />
<xsl:sort select="#*[name()=$sortbysecond]" order="{$order}" />
</xsl:apply-templates>
Try this XSLT...
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:param name="sortby" select="'employee_number'"/>
<xsl:param name="sortbysecond" select="'employee_number'"/>
<xsl:param name="order" select="'descending'"/>
<xsl:template match="employees">
<employees>
<xsl:apply-templates select="employee">
<xsl:sort select="#*[name()=$sortby]" order="{$order}" />
<xsl:sort select="#*[name()=$sortbysecond]" order="{$order}" />
</xsl:apply-templates>
</employees>
</xsl:template>
<xsl:template match="employee">
<employee ID="{#ID}"
employee_number="{#employee_number}"
name="{#last_name}, {#first_name}"
date_joining="{#data_joining}"
dte_to_date="{#dte_to_date}"
date_paid="{#date_paid}"
date_paid="{#date_paid}"
amount="{#amount}"
status="{#status}">
</employee>
</xsl:template>
</xsl:stylesheet>
Note the use of Attribute Value Templates, as Michael Kay mentioned in comments, which simplify your XSLT greatly.

How to create Dropdownlist using XSLT C#?

I am working on project used xslt file to display repeated items. as below:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes" />
<xsl:param name="BasePath" select="/" />
<xsl:param name="OffersPerPage" select="4" />
<xsl:template match="/" xml:space="default">
<div class="offers_section">
<script>
$(document).ready(function() {
$(".offers_page").hide();
$("#OfferPage1").show();
});
function OffersPageChange(CurrentPage, NewPage)
{
$("#OfferPage" + CurrentPage).hide();
$("#OfferPage" + NewPage).show();
$("$offers_section").focus();
return false;
}
</script>
<xsl:choose>
<xsl:when test="count(//Offers/Offer) > 0">
<xsl:for-each select="//Offers/Offer[(position()) mod $OffersPerPage = 1 or position = 1]">
<xsl:variable name="page" select="position()" />
<xsl:variable name="lastpage" select="last()" />
<div class="offers_page"><xsl:attribute name="id">OfferPage<xsl:value-of select="$page" /></xsl:attribute>
<div class="offers_paging">
<xsl:if test="$page > 1">
<xsl:attribute name="onclick">return OffersPageChange(<xsl:value-of select="$page" />, <xsl:value-of select="$page - 1" />)</xsl:attribute>< Previous
</xsl:if>
<xsl:if test="$page < $lastpage">
<xsl:attribute name="onclick">return OffersPageChange(<xsl:value-of select="$page" />, <xsl:value-of select="$page + 1" />)</xsl:attribute>Next >
</xsl:if>
<br /><br />
<xsl:if test="$lastpage != 1">
<xsl:for-each select="//Offers/Offer">
<xsl:if test="(position() - 1) mod $OffersPerPage = 0">
<xsl:attribute name="class"><xsl:choose><xsl:when test="(position() - 1) div $OffersPerPage + 1 = $page">offers_page_number_active</xsl:when><xsl:otherwise>offers_page_number</xsl:otherwise></xsl:choose></xsl:attribute><xsl:attribute name="onclick">return OffersPageChange(<xsl:value-of select="$page" />, <xsl:value-of select="(position() - 1) div $OffersPerPage + 1" />)</xsl:attribute><xsl:value-of select="(position() - 1) div $OffersPerPage + 1" />
</xsl:if>
</xsl:for-each>
<br /><br />
</xsl:if>
</div>
<xsl:for-each select=". | following-sibling::Offer[(position()) < $OffersPerPage]" >
<div class="offers_offer">
<h2><xsl:value-of select="Partner" /></h2>
<xsl:if test="ImageSource != ''">
<div class="offers_image_container">
<div class="offers_image">
<img width="100%"><xsl:attribute name="src"><xsl:value-of select="$BasePath" />portals/<xsl:value-of select="ImageSource" /></xsl:attribute></img>
</div>
<div class="offers_image_overlay">
<img width="100%" height="33" alt=""><xsl:attribute name="src"><xsl:value-of select="$BasePath" />portals/_default/skins/images/offer%20top%20swoop.png</xsl:attribute></img>
<img width="100%" height="126" style="position:absolute;bottom:0;left:0;right:0;" alt=""><xsl:attribute name="src"><xsl:value-of select="$BasePath" />portals/_default/skins/images/offer%20bottom%20swoop.png</xsl:attribute></img>
</div>
</div>
</xsl:if>
<xsl:if test="Description != ''">
<div class="offers_description">
<xsl:value-of select="Description" /><br />
</div>
</xsl:if>
<xsl:if test="LegalInformation != '' and LegalOnOfferPage = 'True'">
<div class="offers_legal">
<xsl:value-of select="LegalInformation" /><br />
</div>
</xsl:if>
<xsl:if test="Facebook != '' or Twitter != ''">
<div class="offers_social_media">
Follow us on:<br />
<div class="social_media_links">
<xsl:if test="Facebook != ''">
<a class="facebook_logo" style="float:none;" target="_blank" title="Facebook"><xsl:attribute name="href"><xsl:value-of select="Facebook" /></xsl:attribute></a>
</xsl:if>
<xsl:if test="Twitter != ''">
<a class="twitter_logo" style="float:none;" target="_blank" title="Twitter"><xsl:attribute name="href">https://www.twitter.com/<xsl:value-of select="Twitter" /></xsl:attribute></a>
</xsl:if>
</div>
</div>
</xsl:if>
<xsl:if test="UrlText != ''">
<div class="offers_url">
<a target="_blank"><xsl:attribute name="href"><xsl:value-of select="Url" /></xsl:attribute><xsl:value-of select="UrlText" /></a>
</div>
</xsl:if>
<xsl:if test="Email != ''">
<div class="offers_email">
Email: <a><xsl:attribute name="href">mailto:<xsl:value-of select="Email" /></xsl:attribute><xsl:value-of select="Email" /></a>
</div>
</xsl:if>
<xsl:if test="Phone != ''">
<div class="offers_phone">
Tel no: <strong><xsl:value-of select="Phone" /></strong>
</div>
</xsl:if>
</div>
</xsl:for-each>
<xsl:if test="$lastpage > 1">
<div class="offers_paging">
<xsl:if test="$lastpage != 1">
<xsl:for-each select="//Offers/Offer">
<xsl:if test="(position() - 1) mod $OffersPerPage = 0">
<xsl:attribute name="class"><xsl:choose><xsl:when test="(position() - 1) div $OffersPerPage + 1 = $page">offers_page_number_active</xsl:when><xsl:otherwise>offers_page_number</xsl:otherwise></xsl:choose></xsl:attribute><xsl:attribute name="onclick">return OffersPageChange(<xsl:value-of select="$page" />, <xsl:value-of select="(position() - 1) div $OffersPerPage + 1" />)</xsl:attribute><xsl:value-of select="(position() - 1) div $OffersPerPage + 1" />
</xsl:if>
</xsl:for-each>
<br /><br />
</xsl:if>
<xsl:if test="$page > 1">
<xsl:attribute name="onclick">return OffersPageChange(<xsl:value-of select="$page" />, <xsl:value-of select="$page - 1" />)</xsl:attribute>< Previous
</xsl:if>
<xsl:if test="$page < $lastpage">
<xsl:attribute name="onclick">return OffersPageChange(<xsl:value-of select="$page" />, <xsl:value-of select="$page + 1" />)</xsl:attribute>Next >
</xsl:if>
</div>
</xsl:if>
</div>
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<div class="offers_not_available">
Sorry, no offers are currently available in this category
</div>
</xsl:otherwise>
</xsl:choose>
</div>
Code Behind Code is :
void Load_Category(int CategoryId)
{
string skinPath = PortalSettings.ActiveTab.SkinPath;
XDocument XDocOffers = new XDocument(new XElement("Offers"));
SqlDataProvider provider = new SqlDataProvider();
SqlConnection SQLConnection = new SqlConnection(provider.ConnectionString);
SQLConnection.Open();
SqlConnection SQLConnectionAnswers = new SqlConnection(provider.ConnectionString);
SQLConnectionAnswers.Open();
SqlCommand sqlComm = new SqlCommand("CIDOTOffersGetOffersByCategory", SQLConnection);
sqlComm.CommandType = CommandType.StoredProcedure;
sqlComm.Parameters.Add(new SqlParameter("#CategoryId", SqlDbType.Int)).Value = CategoryId;
SqlDataReader OffersReader = sqlComm.ExecuteReader();
string OfferId;
string Partner;
string Description;
string ImageSource;
string Url;
string UrlText;
string Email;
string Phone;
string LegalInformation;
string Facebook;
string Twitter;
string LegalOnOfferPage;
string onclick;
string Emailonclick;
while (OffersReader.Read())
{
OfferId = OffersReader["OfferId"].ToString();
Partner = OffersReader["Partner"].ToString();
Description = OffersReader["Description"].ToString();
ImageSource = OffersReader["ImageSource"].ToString();
Url = OffersReader["Url"].ToString();
UrlText = OffersReader["UrlText"].ToString();
Email = OffersReader["Email"].ToString();
Phone = OffersReader["Phone"].ToString();
LegalInformation = OffersReader["LegalInformation"].ToString();
Facebook = OffersReader["Facebook"].ToString();
Twitter = OffersReader["Twitter"].ToString();
LegalOnOfferPage = OffersReader["LegalOnOfferPage"].ToString();
onclick = "_gaq.push(['_trackEvent', 'Book Now', 'click', '" + Partner + "']);";
Emailonclick = "_gaq.push(['_trackEvent', 'Email', 'click', '" + Email + "']);";
XElement NextOffer =
new XElement("Offer",
new XElement("OfferId", OfferId),
new XElement("Partner", Partner),
new XElement("Description", Description),
new XElement("ImageSource", ImageSource),
new XElement("Url", Url),
new XElement("UrlText", UrlText),
new XElement("Email", Email),
new XElement("Phone", Phone),
new XElement("LegalInformation", LegalInformation),
new XElement("Facebook", Facebook),
new XElement("Twitter", Twitter),
new XElement("LegalOnOfferPage", LegalOnOfferPage),
new XElement("onclick", onclick),
new XElement("Emailonclick", Emailonclick)
);
XDocOffers.Element("Offers").Add(NextOffer);
}
OffersReader.Close();
SQLConnection.Close();
string XSLTFile = Server.MapPath(skinPath + "xslt/offers.xslt");
if (File.Exists(XSLTFile))
{
StringWriter XSLTOutput = new StringWriter();
XmlWriter XMLOutput = XmlWriter.Create(XSLTOutput);
// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(XSLTFile);
XsltArgumentList ArgumentsQA = new XsltArgumentList();
if (Settings.ContainsKey("OffersPerPage"))
{
ArgumentsQA.AddParam("OffersPerPage", "", Settings["OffersPerPage"].ToString());
}
else
{
ArgumentsQA.AddParam("OffersPerPage", "", "4");
}
ArgumentsQA.AddParam("BasePath", "", "/");
// Execute the transform and output the results to a writer.
xslt.Transform(XDocOffers.CreateReader(), ArgumentsQA, XMLOutput);
//Output.Controls.Add(new LiteralControl(XSLTOutput.ToString().Replace("&", "&")));
Output.Controls.Add(new LiteralControl(HttpUtility.HtmlDecode(XSLTOutput.ToString())));
}
else
{
Output.Controls.Add(new LiteralControl("Cannot find XSLT file"));
}
}
I have never worked with xslt before, now i want to add a dropdownlist to the page and need to create a search for the selected value from the repeated items in the page body.
My questions are:
how can i create a dropdownlist in xslt.
i have tried the below links but it didn't work for me.
Generate dynamic dropdown in xslt using c#
how to create a event that will search from repeated items. is there any way by which i can call the dropdown's selectedindex change event.?
please help.
A DropDownList you can create like
<asp:DropDownList xmlns:asp="System.Web.UI.WebControls" ID="TheDdl" OnSelectedIndexChanged="Selection_Change" runat="server">
<asp:ListItem Value="1" Text="Text 1" />
<asp:ListItem Value="2" Text="Text 2" />
<asp:ListItem Value="3" Text="Text 3" />
</asp:DropDownList>
The Code behind Looks like
void Selection_Change(Object sender, EventArgs e)
{
// do something ...
}
Xslt just transforms some source XML into some formatted text, usually HTML or XML. This xslt of yours is creating html code, some < div class="offers_section">. I see there's some links being bound inside the xslt code.
This html code being generated is stored inside the string XSLTOutput.ToString(), which is later inserted into the ASP page as a literal control. The code behind is creating the source XML document XDocOffers by retrieving some data from a database.
You could edit the xslt code which has been provided and to allow it to insert html controls < select> and < option>, instead of going for the asp's < asp:dropdownlist>.
If you want to use some < asp:dropdownlist> control, I guess you're trying to use XDocOffers as the source of data. If not you'd have to do your own code to query from the database.
You can run the code and watch XDocOffers XML document, its structure. Then you can ask specifically which is the member you want to use as the dropdown key, and which as the dropdown value. And get specifically into the matter of the dropdown control.

How to display alternately rows design using XSLt file in C#?

I have project used a xslt file to display records using below code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes" />
<xsl:param name="BasePath" select="/" />
<xsl:param name="OffersPerPage" select="4" />
<xsl:template match="/" xml:space="default">
<div class="offers_section">
<script>
$(document).ready(function() {
$(".offers_page").hide();
$("#OfferPage1").show();
});
function OffersPageChange(CurrentPage, NewPage)
{
$("#OfferPage" + CurrentPage).hide();
$("#OfferPage" + NewPage).show();
$("$offers_section").focus();
return false;
}
</script>
<xsl:choose>
<xsl:when test="count(//Offers/Offer) > 0">
<xsl:for-each select="//Offers/Offer[(position()) mod $OffersPerPage = 1 or position = 1]">
<xsl:variable name="page" select="position()" />
<xsl:variable name="lastpage" select="last()" />
<div class="offers_page"><xsl:attribute name="id">OfferPage<xsl:value-of select="$page" /></xsl:attribute>
<div class="offers_paging">
<xsl:if test="$page > 1">
<xsl:attribute name="onclick">return OffersPageChange(<xsl:value-of select="$page" />, <xsl:value-of select="$page - 1" />)</xsl:attribute>< Previous
</xsl:if>
<xsl:if test="$page < $lastpage">
<xsl:attribute name="onclick">return OffersPageChange(<xsl:value-of select="$page" />, <xsl:value-of select="$page + 1" />)</xsl:attribute>Next >
</xsl:if>
<br /><br />
<xsl:if test="$lastpage != 1">
<xsl:for-each select="//Offers/Offer">
<xsl:if test="(position() - 1) mod $OffersPerPage = 0">
<xsl:attribute name="class"><xsl:choose><xsl:when test="(position() - 1) div $OffersPerPage + 1 = $page">offers_page_number_active</xsl:when><xsl:otherwise>offers_page_number</xsl:otherwise></xsl:choose></xsl:attribute><xsl:attribute name="onclick">return OffersPageChange(<xsl:value-of select="$page" />, <xsl:value-of select="(position() - 1) div $OffersPerPage + 1" />)</xsl:attribute><xsl:value-of select="(position() - 1) div $OffersPerPage + 1" />
</xsl:if>
</xsl:for-each>
<br /><br />
</xsl:if>
</div>
<xsl:for-each select=". | following-sibling::Offer[(position()) < $OffersPerPage]" >
<div class="offers_offer">
<h2><xsl:value-of select="Partner" /></h2>
<xsl:if test="ImageSource != ''">
<div class="offers_image_container">
<div class="offers_image">
<img width="100%"><xsl:attribute name="src"><xsl:value-of select="$BasePath" />portals/7/<xsl:value-of select="ImageSource" /></xsl:attribute></img>
</div>
<div class="offers_image_overlay">
<img width="100%" height="33" alt=""><xsl:attribute name="src"><xsl:value-of select="$BasePath" />portals/_default/skins/onlyin/images/offer%20top%20swoop.png</xsl:attribute></img>
<img width="100%" height="126" style="position:absolute;bottom:0;left:0;right:0;" alt=""><xsl:attribute name="src"><xsl:value-of select="$BasePath" />portals/_default/skins/onlyin/images/offer%20bottom%20swoop.png</xsl:attribute></img>
</div>
</div>
</xsl:if>
<xsl:if test="Description != ''">
<div class="offers_description">
<xsl:value-of select="Description" /><br />
</div>
</xsl:if>
<xsl:if test="LegalInformation != '' and LegalOnOfferPage = 'True'">
<div class="offers_legal">
<xsl:value-of select="LegalInformation" /><br />
</div>
</xsl:if>
<xsl:if test="Facebook != '' or Twitter != ''">
<div class="offers_social_media">
Follow us on:<br />
<div class="social_media_links">
<xsl:if test="Facebook != ''">
<a class="facebook_logo" style="float:none;" target="_blank" title="Facebook"><xsl:attribute name="href"><xsl:value-of select="Facebook" /></xsl:attribute></a>
</xsl:if>
<xsl:if test="Twitter != ''">
<a class="twitter_logo" style="float:none;" target="_blank" title="Twitter"><xsl:attribute name="href">https://www.twitter.com/<xsl:value-of select="Twitter" /></xsl:attribute></a>
</xsl:if>
</div>
</div>
</xsl:if>
<xsl:if test="UrlText != ''">
<div class="offers_url">
<a target="_blank"><xsl:attribute name="onclick"><xsl:value-of select="onclick" /></xsl:attribute><xsl:attribute name="href"><xsl:value-of select="Url" /></xsl:attribute><xsl:value-of select="UrlText" /></a>
</div>
</xsl:if>
<xsl:if test="Email != ''">
<div class="offers_email">
Email: <a> <xsl:attribute name="onclick"><xsl:value-of select="Emailonclick" /></xsl:attribute><xsl:attribute name="href">mailto:<xsl:value-of select="Email" /></xsl:attribute><xsl:value-of select="Email" /></a>
</div>
</xsl:if>
<xsl:if test="Phone != ''">
<div class="offers_phone">
Tel no: <strong><xsl:value-of select="Phone" /></strong>
</div>
</xsl:if>
</div>
</xsl:for-each>
<xsl:if test="$lastpage > 1">
<div class="offers_paging">
<xsl:if test="$lastpage != 1">
<xsl:for-each select="//Offers/Offer">
<xsl:if test="(position() - 1) mod $OffersPerPage = 0">
<xsl:attribute name="class"><xsl:choose><xsl:when test="(position() - 1) div $OffersPerPage + 1 = $page">offers_page_number_active</xsl:when><xsl:otherwise>offers_page_number</xsl:otherwise></xsl:choose></xsl:attribute><xsl:attribute name="onclick">return OffersPageChange(<xsl:value-of select="$page" />, <xsl:value-of select="(position() - 1) div $OffersPerPage + 1" />)</xsl:attribute><xsl:value-of select="(position() - 1) div $OffersPerPage + 1" />
</xsl:if>
</xsl:for-each>
<br /><br />
</xsl:if>
<xsl:if test="$page > 1">
<xsl:attribute name="onclick">return OffersPageChange(<xsl:value-of select="$page" />, <xsl:value-of select="$page - 1" />)</xsl:attribute>< Previous
</xsl:if>
<xsl:if test="$page < $lastpage">
<xsl:attribute name="onclick">return OffersPageChange(<xsl:value-of select="$page" />, <xsl:value-of select="$page + 1" />)</xsl:attribute>Next >
</xsl:if>
</div>
</xsl:if>
</div>
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<div class="offers_not_available">
Sorry, no offers are currently available in this category
</div>
</xsl:otherwise>
</xsl:choose>
</div>
Code behind code is:
void Load_Category(int CategoryId)
{
string skinPath = PortalSettings.ActiveTab.SkinPath;
XDocument XDocOffers = new XDocument(new XElement("Offers"));
SqlDataProvider provider = new SqlDataProvider();
SqlConnection SQLConnection = new SqlConnection(provider.ConnectionString);
SQLConnection.Open();
SqlConnection SQLConnectionAnswers = new SqlConnection(provider.ConnectionString);
SQLConnectionAnswers.Open();
SqlCommand sqlComm = new SqlCommand("OffersGetOffersByCategory", SQLConnection);
sqlComm.CommandType = CommandType.StoredProcedure;
sqlComm.Parameters.Add(new SqlParameter("#CategoryId", SqlDbType.Int)).Value = CategoryId;
SqlDataReader OffersReader = sqlComm.ExecuteReader();
string OfferId;
string Partner;
string Description;
string ImageSource;
string Url;
string UrlText;
string Email;
string Phone;
string LegalInformation;
string Facebook;
string Twitter;
string LegalOnOfferPage;
string onclick;
string Emailonclick;
while (OffersReader.Read())
{
OfferId = OffersReader["OfferId"].ToString();
Partner = OffersReader["Partner"].ToString();
Description = OffersReader["Description"].ToString();
ImageSource = OffersReader["ImageSource"].ToString();
Url = OffersReader["Url"].ToString();
UrlText = OffersReader["UrlText"].ToString();
Email = OffersReader["Email"].ToString();
Phone = OffersReader["Phone"].ToString();
LegalInformation = OffersReader["LegalInformation"].ToString();
Facebook = OffersReader["Facebook"].ToString();
Twitter = OffersReader["Twitter"].ToString();
LegalOnOfferPage = OffersReader["LegalOnOfferPage"].ToString();
onclick = "_gaq.push(['_trackEvent', 'Book Now', 'click', '" + Partner + "']);";
Emailonclick = "_gaq.push(['_trackEvent', 'Email', 'click', '" + Email + "']);";
XElement NextOffer =
new XElement("Offer",
new XElement("OfferId", OfferId),
new XElement("Partner", Partner),
new XElement("Description", Description),
new XElement("ImageSource", ImageSource),
new XElement("Url", Url),
new XElement("UrlText", UrlText),
new XElement("Email", Email),
new XElement("Phone", Phone),
new XElement("LegalInformation", LegalInformation),
new XElement("Facebook", Facebook),
new XElement("Twitter", Twitter),
new XElement("LegalOnOfferPage", LegalOnOfferPage),
new XElement("onclick", onclick),
new XElement("Emailonclick", Emailonclick)
);
XDocOffers.Element("Offers").Add(NextOffer);
}
OffersReader.Close();
SQLConnection.Close();
string XSLTFile = Server.MapPath(skinPath + "xslt/offers.xslt");
if (File.Exists(XSLTFile))
{
StringWriter XSLTOutput = new StringWriter();
XmlWriter XMLOutput = XmlWriter.Create(XSLTOutput);
// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(XSLTFile);
XsltArgumentList ArgumentsQA = new XsltArgumentList();
if (Settings.ContainsKey("OffersPerPage"))
{
ArgumentsQA.AddParam("OffersPerPage", "", Settings["OffersPerPage"].ToString());
}
else
{
ArgumentsQA.AddParam("OffersPerPage", "", "4");
}
ArgumentsQA.AddParam("BasePath", "", "/");
// Execute the transform and output the results to a writer.
xslt.Transform(XDocOffers.CreateReader(), ArgumentsQA, XMLOutput);
//Output.Controls.Add(new LiteralControl(XSLTOutput.ToString().Replace("&", "&")));
Output.Controls.Add(new LiteralControl(HttpUtility.HtmlDecode(XSLTOutput.ToString())));
}
else
{
Output.Controls.Add(new LiteralControl("Cannot find XSLT file"));
}
}
Problem is:
Now display the detail in some different format for alternate row. currently, every offer has image in left side and description in right, for alternate row now i want to display description in left and image in right, i have never used xslt file before, can anyone please help... or suggest me how can achieve this.
waiting for your helpful answers..
i have solved out this problem..
Here is the solution, we didn't need to changes anything in c# code(code behind), we have just changed the xslt file t do this, as xslt file number of inbuilt functions to do.
I have used mod as below:
<xsl:for-each select=". | following-sibling::Offer[(position()) < $OffersPerPage]" >
<xsl:choose>
<xsl:when test="position() mod 2 = 1">
data 1
</xsl:when>
<xsl:otherwise>
data 2
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
That's all.....

Categories