I am trying to bind XML data to Dropdownlist
XElement xDoc = XElement.Parse(QContent.OuterXml);
Here is what my xDoc contains
<root xmlns="">
<item value="-1" text="Select" />
<item value="1" text="$30,000" />
<item value="2" text="$50,000" />
</root>
Query to extract the data into a Listitem :
var query = from xEle in xDoc.Descendants("root")
select new ListItem(xEle.Attribute("value").Value , xEle.Attribute("text").Value);
This yields no results. Please advice.
Thanks in advance
BB
Put your XML file inside App_Data
or anywhere in program and in MapPath
.
Assign their path and also assign the name of your first XML column in the last line.
Here I'm using "code" because it is my first XML column and country is the name of the column I want to show in my dropdownlist
.
private void BindCountry()
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~//App_Data//countries.xml"));
foreach (XmlNode node in doc.SelectNodes("//country"))
{
ddlcountry.Items.Add(new ListItem(node.InnerText, node.Attributes["code"].InnerText));
}
}
You can change your LINQ query to the following which will return all the nodes under root
and return new items with the value/text pairs that you are trying to bind to.
var query = from xEle in xDoc.Descendants()
select new {value = xEle.Attribute("value").Value , text = xEle.Attribute("text").Value};
Then set up your bindings as follows including collapsing the query to a list.
ddlList.DataValueField = "value";
ddlList.DataTextField = "text";
ddlList.DataSource = query.ToList();
ddlList.DataBind();