Multiple child elements of XML into one line of combobox

时间:2015-06-25 18:15:22

标签: c# xml winforms

I have some XML that looks similar to this:

<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>

For every ID number, the example above includes ID 1. I'd like to include all of its child elements into one line of a combobox.

To look similar to this

  1. DriverSheave = 1vp34, Driver Bushing = (nothing)/0, DrivenSheave = AK49,
  2. etc...

I have looked at Getting XML data into combobox, but it only shows how to get single items from XML into combo boxes.

1 个答案:

答案 0 :(得分:2)

So, for each entry, we have:

  • A Solution element containing:
    • An ID element
    • Some Property elements containing:
    • A Name element
    • A Value element (optional)

I would first transform the XML to that structure in memory, and then you can convert it to strings. A LINQ query should make that easy - you could either create classes, or just use anonymous types if this is all you need it for:

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

Then you could use:

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

(This is untested, and it may have some bracket mismatches, but should give you the basic idea.)