2

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

2
  • So what is the problem with it? Commented Jan 4, 2014 at 8:56
  • I wanted to be able to read two elements at the same time (I have two loops foreach). The solution proposed by Sergey avoided that, having only one loop. Commented Jan 4, 2014 at 10:08

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Lovely solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.