我遇到了从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_PlantedACRECRNP索引。我只希望显示文本Acreage_Corn_Planted。
答案 0 :(得分:-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();
}