Alex Gordon
Alex Gordon

Reputation: 60751

how to load xml file into dropdownlist in asp.net

the file looks like this:

    <?xml version="1.0" encoding="utf-8" ?>
    <data>
    <a7190>
    <food>Almond</food>
    <food>American Cheese</food>
    <food>Apple</food>
    </a7190>
    <a7191>
    <food>Trout</food>
    <food>Tuna</food>
</a7191>
    <food>Turkey</food>
    <food>Wheat</food>
<a7193>
    <food>Yogurt</food>
    </a7193>
    </data>

i ONLY need to load the a7190, a7191, etc

i am using asp.net and although i am pretty well-versed with vb.net, asp.net is completely new to me

Upvotes: 1

Views: 5535

Answers (2)

Matthew Jones
Matthew Jones

Reputation: 26190

This article describes how to do this using the XMLDataSource present in ASP.NET.

EDIT: I just ran the code through the C# to VB converter located here, so the syntax is not guaranteed.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not IsPostBack Then
         'call to the function to populate dropdownlist from xml'
         PopulateDDLFromXMLFile()
    End If
End Sub

    'populates the dropdownlist from xml file'
    Public Sub PopulateDDLFromXMLFile()
        Dim ds As New DataSet()
        ds.ReadXml(MapPath("~/Resources/XMLFile.xml"))
        
        'get the dataview of table "Country", which is default table name'
        Dim dv As DataView = ds.Tables("Country").DefaultView
        'or we can use:'
        'DataView dv = ds.Tables[0].DefaultView;'
        
        'Now sort the DataView vy column name "Name"'
        dv.Sort = "Name"
        
        'now define datatext field and datavalue field of dropdownlist'
        ddlCountry.DataTextField = "Name"
        ddlCountry.DataValueField = "ID"
        
        'now bind the dropdownlist to the dataview'
        ddlCountry.DataSource = dv
        ddlCountry.DataBind()
    End Sub

Upvotes: 3

Brian Sullivan
Brian Sullivan

Reputation: 28573

I don't know that ASP.NET gives you any tools here that you wouldn't have in a console app or Windows app. You might try using LINQ-to-XML to pull out the elements you need, and bind that result as a datasource to your dropdown.

Upvotes: 1

Related Questions