Nick_F
Nick_F

Reputation: 1117

C# XML - reading multiple elements at once

I have this xml document:

<?xml version="1.0" ?>
<object>
    <name>Sphere</name>
    <material>Steel</material>
    <device Id="01">
        <model>Model 1</model>
        <color>Red</color>
    </device>
    <device Id="02">
        <model>Model 2</model>
        <color>Blue</color>
    </device>
</object>

I want to be able to read in a for loop both the model and the color of each device. My code can only read only one value at a time (either model or value) and I have to go through the loop twice.

I expect there should be a more elegant solution.

var xDoc = XDocument.Load(@"C:\_Projects\AProjectsCS\XML_Tutorial\Sample.xml");

IEnumerable<XElement> list1 = xDoc.Root.Descendants("model");  
IEnumerable<XElement> list2 = xDoc.XPathSelectElements("//color");  

foreach (XElement el in list1)
    Console.WriteLine(el.Value);

foreach (XElement el in list2)
    Console.WriteLine(el.Value);

Thanks, Nick

Upvotes: 2

Views: 3648

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

Just select both model and color elements values from each device element (you can use either anonymous type, as below, or create your custom Device class to hold this data):

var xDoc = XDocument.Load(@"C:\_Projects\AProjectsCS\XML_Tutorial\Sample.xml");
var devices = from d in xDoc.Root.Elements("device")
              select new {
                  Model = (string)d.Element("model"),
                  Color = (string)d.Element("color")
              };

foreach(var device in devices)
{
    Console.WriteLine(device.Model);
    Console.WriteLine(device.Color);
}

Upvotes: 2

Related Questions