简体   繁体   English

使用C#将xml文件中的节点名称添加到组合框中

[英]add node names from an xml file into a combobox using c#

Im using c#.net windows form applpication. 我正在使用c#.net Windows窗体应用程序。 I have an xml file which contains many nodes. 我有一个包含许多节点的xml文件。 How can I get the names of those nodes into a combobox. 如何将这些节点的名称放入组合框。 If possible avoid duplicate names. 如果可能,请避免使用重复的名称。

If you're using .NET 3.5 you can use LINQ to XML to select your nodes. 如果使用的是.NET 3.5,则可以使用LINQ to XML选择节点。

Alternatively, or if you're not using .NET 3.5, you can use System.Xml.XPath to select your nodes. 或者,或者如果您不使用.NET 3.5,则可以使用System.Xml.XPath选择节点。

After selecting your nodes you can use a foreach on them and insert them one by one in that loop. 选择节点后,您可以在它们上使用foreach并在该循环中一个接一个地插入它们。 Alternatively if you have them stored in a List<> you can use ForEach for cleaner code. 或者,如果将它们存储在List<> ,则可以使用ForEach来获得更清晰的代码。

You can do this using LINQ to XML: 您可以使用LINQ to XML来做到这一点:

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

This should suit your needs without using LINQ etc: 无需使用LINQ等即可满足您的需求:

        foreach (XmlNode node in my_XML_Doc)
        {
            if (!ComboBox1.Items.Contains(node.Name))
            {
                ComboBox1.Items.Add(node.Name);
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM