views:

68

answers:

1

I am having trouble wrapping my mind around how to do this in linq.

How can i convert this:

<mytags>
    <tag1>hello</tag1>
    <tag2>hello</tag2>
    <tag1>MissingTag</tag1>
    <tag1>Goodbye</tag1>
    <tag2>Goodbye</tag2>
</mytags>

to this

List<MyObject>

public class MyObject
{
    public tag1;
    public tag2;
}
+3  A: 

Try this out:

string input = "<mytags><tag1>hello</tag1><tag2>hello</tag2><tag1>MissingTag</tag1><tag1>Goodbye</tag1><tag2>Goodbye</tag2></mytags>";
var xml = XElement.Parse(input);
var list = (from x in xml.Elements("tag1")
           let next = x.NextNode as XElement
           select new MyObject
            {
                Tag1 = x.Value,
                Tag2 = (next != null && next.Name == "tag2") ? next.Value : ""
            }).ToList();

This only works for scenarios where tag2 is missing, not the other way around.

Ahmad Mageed
What does `.Dump()` do?
Dennis Palmer
@Dennis I guess I wasn't quick enough ;) I removed it from my sample but it's actually an extension method in LINQPad that dumps an object to the output window. Very handy for quick debugging. You can get LINQPad to try it out or download the VS2008 C# samples and it's included as the ObjectWriter.
Ahmad Mageed
I was typing an answer when you're came through, so I saw it right away. I don't work with C# all the time, so I wasn't sure the best way to do this. Your answer looks great!
Dennis Palmer
@Dennis it's a little tricky since all the elements are direct descendants of the root. If they were children of another element it would've been easier. BTW the project is called `ObjectDumper`, not ObjectWriter. You can compile it from the samples then reference it in other projects. Making it an extension method is much more convenient. The time limit for my last comment expired so I can't go back and edit it.
Ahmad Mageed