0

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

1
  • 1
    Do you have to do it this way? Can't you just create a dataset and Use the dataset to read the XML file and finally bind the dataset to the drop down list and you're done. Commented Jan 20, 2012 at 23:21

2 Answers 2

2

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));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.