AndrewR
AndrewR

Reputation: 624

LINQ to XML parsing single object

I am trying to parse XML document like this:

<root>
    <first>1</first>
    <second>2</second>
</root>

To structure like this:

class SomeClass
{
    ...

    public string First;
    public string Second;
}

but as far as I understood, I can create new object only in select statement, which only can be applied to collection and root element is not a collection.

Of course, I can select fields separately like:

new SomeClass(doc.Element("first").Value, doc.Element("second").Value);

But I'm really interested if is it possible to do it in one LINQ statement (using doc variable only once and creating object inside the LINQ statement)?

In other words: is it possible to create an object not in Select() method?

Upvotes: 0

Views: 74

Answers (1)

Riv
Riv

Reputation: 1859

The root element may not be a collection, but when you parse the xml, your doc variable is a collection of elements, including root element. So you can still use Select:

string xml = @"<root><first>1</first><second>2</second></root>";

var doc = XDocument.Parse(xml);
var collectionOfSomeClass = doc.Elements()
                            .Select(x => new SomeClass 
                                        { First = x.Element("first").Value, 
                                          Second = x.Element("second").Value 
                                        });

Upvotes: 1

Related Questions