How to populate a drop down list from an XML file in .NET
I know this is not rocket science but it’s actually something I’d never had to do until recently. Normally I populate my drop down lists (and repeaters, etc etc) using data from databases, not XML.
However, fear not. Using XML as a datasource in .NET is super easy. Here is one way to do it:
1 2 3 4 5 6 7 8 | XmlDataSource source = new XmlDataSource(); source.DataFile = Server.MapPath("Values.xml"); source.XPath = "ParentElement/ValueList/ValueItem"; myDropDownList.DataSource = source; myDropDownList.DataTextField = "Text"; myDropDownList.DataValueField = "Value"; myDropDownList.DataBind(); |
And your xml file, Values.xml, may look something like:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?> <ParentElement> <ValueList> <ValueItem Text="Item 1" Value="1" /> <ValueItem Text="Item 2" Value="2" /> </ValueList> </ParentElement> |
Happy coding!
Read More
