将XML的多个子元素合并到一行组合框中



我有一些类似于以下内容的XML:

<SolutionString>
  <Solutions>
    <Solution>
      <ID>1</ID>
      <Property>
        <Name>DriverSheave</Name>
        <Value>1VP34</Value>
      </Property>
      <Property>
        <Name>DriverBushing</Name>
        <Value>
        </Value>
      </Property>
      <Property>
        <Name>DrivenSheave</Name>
        <Value>AK49</Value>
      </Property>
      <Property>
        <Name>DrivenBushing</Name>
        <Value>
        </Value>
      </Property>
    </Solution>
    <Solution>
      <ID>2</ID>

对于每个ID号,上面的示例包括ID 1。我想把它的所有子元素都包含在一行组合框中。

看起来与此相似

  1. 传动带=1vp34,传动衬套=(无)/0,传动升沉=AK49
  2. 等等

我已经研究过将XML数据放入组合框,但它只展示了如何将XML中的单个项放入组合框。

因此,对于每个条目,我们都有:

  • 一种Solution元素,包含:
    • ID元素
    • 一些Property元素包含:
    • Name元素
    • Value元素(可选)

我会首先将XML转换为内存中的那个结构,然后可以将其转换为字符串。LINQ查询应该让这变得很容易——你可以创建类,或者只使用匿名类型,如果这就是你所需要的:

var doc = XDocument.Load(file);
var solutions = docs
    .Descendants("Solution")
    .Select(x => new {
        ID = (string) x.Element("ID"),
        Properties = x.Elements("Property").Select(p => new {
            Name = (string) p.Element("Name"),
            Value = (string) p.Element("Value")
        }).ToList()
    }).ToList();

然后你可以使用:

var items = solutions
   .Select(s => new {
       ID = s.ID,
       Text = string.Format("{0}. {1}", s.ID,
           string.Join(", ", s.Properties
                              .Select(p => string.Format("{0} = {1}",
                                                         p.Name,
                                                         p.Value ?? "(nothing/0)"))))
   }).ToArray();
comboBox.DisplayMember = "Text";
comboBox.ValueMember = "ID";
comboBox.Items.AddRange(items);

(这是未经测试的,可能有一些括号不匹配,但应该会给你基本的想法。)

最新更新