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
I have looked at Getting XML data into combobox, but it only shows how to get single items from XML into combo boxes.
So, for each entry, we have:
Solution
element containing:
ID
elementProperty
elements containing:Name
elementValue
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.)
See more on this question at Stackoverflow