views:

132

answers:

3

Im using c#.net windows form applpication. I have an xml file which contains many nodes. How can I get the names of those nodes into a combobox. If possible avoid duplicate names.

A: 

If you're using .NET 3.5 you can use LINQ to XML to select your nodes.

Alternatively, or if you're not using .NET 3.5, you can use System.Xml.XPath to select your nodes.

After selecting your nodes you can use a foreach on them and insert them one by one in that loop. Alternatively if you have them stored in a List<> you can use ForEach for cleaner code.

Brian R. Bondy
A: 

You can do this using LINQ to XML:

combobox.DataSource = XDocument.Load(path)
        .Descendants
        .Select(n => n.Name.LocalName)
        .Distinct()
        .ToArray();
SLaks
A: 

This should suit your needs without using LINQ etc:

        foreach (XmlNode node in my_XML_Doc)
        {
            if (!ComboBox1.Items.Contains(node.Name))
            {
                ComboBox1.Items.Add(node.Name);
            }
        }
Yoda
This won't compile. (What's `my_XML_doc`?)
SLaks