简体   繁体   中英

Linq2XML separate keys into List

I want to read a config.xml and put each item into a combobox so that the XML file is the datasource. This is my code, which only gives me one entry in my combobox. How do I separate the keys? This is my filter:

C#

var xmlDocument = XDocument.Load(configfile);
var anredeItems = from key in xmlDocument.Descendants("Anrede")
                  select key.Value.Trim();
anredeNrComboBox.DataSource = anredeItems.ToList();

This is the XML:

<?xml version="1.0"?>
<Config>
    <Anrede>
        <key_1>Herrn</key_1>
        <key_2>Frau</key_2>
        <key_3>Herrn Dr.</key_3>
        <key_4>Frau Dr.</key_4>
        <key_5>Herrn Dr. Med.</key_5>
    </Anrede>
</Config>

Your Descendants("Anrede") query will get you the element Andrede , and reading the Value property of that will return the concatenation of all descendant text nodes, which is what you are seeing in your combo box.

What you want are each of its child element values:

var items - doc.Descendants("Anrede")
    .Elements()
    .Select(x => x.Value.Trim())
    .ToList();

You can change your code like this:

var xmlDocument = XDocument.Load(configfile);
var anredeItems = xmlDocument.Root.Elements("Anrede").Elements().Select(p => p.Value.Trim());
anredeNrComboBox.DataSource = anredeItems.ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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