从C#中的XML填充下拉列表 [英] Populating dropdown from the XML in C#

查看:377
本文介绍了从C#中的XML填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的XML格式,与我和我使用.NET 2.0。

I have got below xml format with me and I am using .NET 2.0.

<?xml version="1.0" encoding="utf-8"?>
<publicationsList>
  <publication tcmid="tcm:0-226-1">
    <name>00 Primary Parent</name>
  </publication>
  <publication tcmid="tcm:0-227-1">
    <name>01 Group Parent</name>
  </publication>
  <publication tcmid="tcm:0-228-1">
    <name>02 Developer Library</name>
  </publication>
  <publication tcmid="tcm:0-229-1">
    <name>03C Content Library</name>
  </publication>
</publicationsList>

现在我想从上面的XML填充我DropDownList的,我的DropDownList的文本将名节点值和DropDownList的值将被使用的方法在C#tcmid属性值。

Now I want to populate my dropdownlist from the above XML, my dropdownlist TEXT will be "name" node value and dropdownlist VALUE will be "tcmid" attribute value using a method in C#.

请建议!!

推荐答案

您可以做这样的事情

使用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的

Update: Using 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();

这篇关于从C#中的XML填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆