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

时间:2011-05-11 04:26:29

标签: c# .net xml

我的xml格式低于我,我使用的是.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填充我的下拉列表,我的下拉列表TEXT将是“name”节点值,而dropdownlist VALUE将是使用C#中的方法的“tcmid”属性值。

请建议!!

5 个答案:

答案 0 :(得分:4)

你可以做这样的事情

使用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();

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您可以尝试以下代码, 我宁愿选择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<string,string>[] GetNames()
    {
        List<KeyValuePair<string,string>> names=new List<KeyValuePair<string,string>>();
        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<string, string>(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<KeyValuePair<string,string>>names=loader.GetNames();
    }
}

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

答案 3 :(得分:0)

我创建了自定义类,用于将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);

希望它对你有所帮助。

答案 4 :(得分:0)

也许这对你有用:

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是:

<?xml version="1.0" encoding="utf-8" ?>
 <items>
    <item>
      <name>Elemento 1</name>
      <value>1</value>
    </item>
  </items>