0

我在绑定 xml 文件中的数据下拉列表时遇到问题。xml 文件看起来像这样;

<agricultural>
<file>
  <text>Acreage_Cotton_Planted</text>
  <value>ACRECOTP Index</value>
</file>
<file>
  <text>Acreage_Corn_Planted</text>
  <value>ACRECRNP Index</value>
</file>
<file>
  <text>Acreage_Soybean_Planted</text>
  <value>ACRESOYP Index</value>
</file>
<file>
  <text>Acreage_Wheat_Planted</text>
  <value>ACREWHTP Index</value>
</file>
</agricultural>

我正在使用此代码从 xml 返回列表

Public Shared Function GetAgDataList(nodestring As String) As List(Of ListItem)
    Dim doc As New XmlDocument()
    'Load XML from the file into XmlDocument object
    doc.Load("~\DataFiles\dataXML.xml") 'this needs to be changed to the server path
    Dim root As XmlNode = doc.DocumentElement
    'Select all nodes with the tag paramter indicated by the nodestring variable
    Dim nodeList As XmlNodeList = root.SelectNodes(nodestring)
    Return (From node As XmlNode In nodeList Let text = node.Attributes.GetNamedItem("text").Value.ToString() Let val = node.Attributes.GetNamedItem("value").Value.ToString() Select New ListItem(text, val)).ToList()
End Function

下拉列表控件不应该只显示文本吗?因为我的下拉列表显示连接在一起的文本和值。例如,Acreage_Corn_PlantedARECCRNP 索引。我只想显示文本 Acreage_Corn_Planted。

4

1 回答 1

-1

您可以使用以下代码:我使用了 LINQ to Entity,它适用于 ASP.NET 3.5 或更高版本:

    using System.Xml.Linq;
public class Item {
    public string Text { get; set; }
    public string Value { get; set; }
}

public class MyPage : Page { 
    XDocument xdoc = XDocument.Load("MyXmlFile.xml");
        var listOfItems = new List<Item>();
        foreach (XElement item in xdoc.Element("agricultural").Elements("file")) {
            listOfItems.Add(new Item() { Text = item.Element("text").Value, Value = item.Element("value").Value });
        }
            myDrp.DataTextField = "Text";
            myDrp.DataValueField = "Value";
            myDrp.DataSource = listOfItems;
            myDrp.DataBind();
}
于 2012-06-10T11:45:54.790 回答