如何将xml文件加载到asp.net的dropdownlist中

时间:2009-06-12 15:37:45

标签: asp.net xml

文件如下所示:

    <?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>

我只需要加载a7190,a7191等

我正在使用asp.net,虽然我对vb.net非常熟悉,但asp.net对我来说是全新的

2 个答案:

答案 0 :(得分:3)

This article描述了如何使用ASP.NET中的XMLDataSource执行此操作。

编辑:我刚刚通过C#到VB转换器located here运行代码,因此无法保证语法。

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

答案 1 :(得分:1)

我不知道ASP.NET为您提供了在控制台应用程序或Windows应用程序中不具备的任何工具。您可以尝试使用LINQ-to-XML来提取所需的元素,并将该结果作为数据源绑定到您的下拉列表。