简体   繁体   English

Linq2XML将密钥分隔成List

[英]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. 我想读取config.xml并将每个项目放入组合框,以便XML文件成为数据源。 This is my code, which only gives me one entry in my combobox. 这是我的代码,在组合框中仅给我一个条目。 How do I separate the keys? 如何分开钥匙? This is my filter: 这是我的过滤器:

C# 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:

<?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. 您的Descendants("Anrede")查询将为您提供元素Andrede ,读取该元素的Value属性将返回所有后代文本节点的串联,这是您在组合框中看到的内容。

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

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

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