在C#中填充XML中的下拉列表

我有以下xml格式,我使用的是.NET 2.0。

   00 Primary Parent   01 Group Parent   02 Developer Library   03C Content Library   

现在我想从上面的XML填充我的下拉列表,我的下拉列表TEXT将是“名称”节点值,而下拉列表VALUE将是使用C#中的方法的“tcmid”属性值。

请建议!!

你可以这样做

使用Linq

 XDocument xDoc = XDocument.Load(@"Yourxmlfile.xml"); var query = from xEle in xDoc.Descendants("publication") select new ListItem(xEle.Element("name").Value, xEle.Attribute("tcmid").Value); ddlList.DataValueField = "value"; ddlList.DataTextField = "text"; ddlList.DataSource = query; ddlList.DataBind(); 

更新:使用XmlDocument

 XmlDocument xDocument = new XmlDocument(); xDocument.Load(@"YourXmlFile.xmll"); foreach (XmlNode node in xDocument.GetElementsByTagName("publication")) { ddlList.Items.Add(new ListItem(node.SelectSingleNode("name").InnerText, node.Attributes["tcmid"].Value)); } ddlList.DataValueField = "value"; ddlList.DataTextField = "text"; ddlList.DataBind(); 

您可以使用Linq-to-XML从xml树中获取所需的值集合,并将其绑定到下拉列表。 请参阅此链接: http : //msdn.microsoft.com/en-us/library/bb387061.aspx

您可以尝试使用代码,我宁愿选择Xpath,因为它更容易阅读。 DocumentLoader类,它从字符串或任何具有有效xml内容的流中加载内容。

 public class DocumentLoader { private readonly string content; public DocumentLoader(Stream stream):this(new StreamReader(stream).ReadToEnd()) { } public DocumentLoader(string content) { this.content = content; } public KeyValuePair[] GetNames() { List> names=new List>(); XmlDocument document=new XmlDocument(); document.LoadXml(this.content); XmlNodeList xmlNodeList = document.SelectNodes("//publication"); if(xmlNodeList!=null) { foreach (XmlNode node in xmlNodeList) { string key = node.InnerText; string value = ""; if (node.Attributes != null) { value = node.Attributes["tcmid"].Value; } names.Add(new KeyValuePair(key,value)); } } return names.ToArray(); } } 

只是一个测试代码。

 public class DocumentLoaderTest { public void Test() { DocumentLoader loader = new DocumentLoader(File.Open("D:\\sampleSource.xml", FileMode.Open)); //now names contains the value of the name element List>names=loader.GetNames(); } } 

已更新以获取Name元素和tcmid属性

我已经创建了自定义类来将XML绑定到DROPDOWN。 自定义类的代码如下

 public class XmlReaderBinder { public static void BindDropDown(ComboBox dd, string elementName, string nodeNameValue, string nodeNameText, string xmlPath) { HttpContext context = HttpContext.Current; XmlTextReader reader = null; ArrayList lstItems = new ArrayList(); string val = String.Empty; string txt = String.Empty; bool inTarget = false; try { reader = new XmlTextReader(xmlPath); //Allow for object to object comparison rather than string comparison object target = reader.NameTable.Add(elementName); object targetVal = reader.NameTable.Add(nodeNameValue); object targetTxt = reader.NameTable.Add(nodeNameText); //Read through the XML stream and find proper tokens while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { //Check attribute names if (reader.Name.Equals(target)) { inTarget = true; //Get attribute values (if any) if (reader.HasAttributes) { if (reader.MoveToAttribute(nodeNameValue)) { val = reader.Value; reader.MoveToElement(); } if (reader.MoveToAttribute(nodeNameText)) { txt = reader.Value; reader.MoveToElement(); } } if (val == "" || txt == "") val = txt = String.Empty; if (val != String.Empty && txt != String.Empty) { ListItem item = new ListItem(txt, val); lstItems.Add(item); //Attribute values override any child nodes values //so if we match on attributes then don't look at any //child nodes inTarget = false; val = txt = String.Empty; } } else if (inTarget) { //Check for child nodes that match if (reader.Name.Equals(targetVal)) { val = reader.ReadString(); if (val == "") val = String.Empty; } if (reader.Name.Equals(targetTxt)) { txt = reader.ReadString(); if (txt == "") txt = String.Empty; } if (val != String.Empty && txt != String.Empty) { ListItem item = new ListItem(txt, val); lstItems.Add(item); val = txt = String.Empty; } } } if (reader.NodeType == XmlNodeType.EndElement || reader.IsEmptyElement) { if (reader.Name.Equals(target)) { inTarget = false; } } } if (lstItems.Count > 0) { foreach (ListItem item in lstItems) { dd.Items.Add(item); } } else { ListItem item = new ListItem("No Data Available", ""); dd.Items.Add(item); } lstItems.Clear(); } catch (Exception exp) { context.Response.Write(exp.Message); } finally { if (reader != null) reader.Close(); } } } 

在创建类之后,您可以像下面提到的那样调用类函数’BindDropDown’。

 XmlReaderBinder.BindDropDown('DROP DOWN NAME', "publicationsList", "publication", "Name", xmlPath); 

希望它对你有所帮助。

也许这对你有用:

 path = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, @"App_Data\Empresas.xml"); ds = new DataSet(); ds.ReadXml(path); ddlEmpresa.DataValueField = "value"; ddlEmpresa.DataTextField = "name"; ddlEmpresa.DataSource = ds; ddlEmpresa.DataBind(); 

而XML是:

    Elemento 1 1