Chris James
Chris James

Reputation: 11731

LINQ to XML getting value

This is a newbie question but I cant seem to find to do the following:

XML is this -

<sets><set><title>hello1</title><images><image>1667</image></images></set></sets>

    foreach (XElement setNode in collectionXML.DescendantNodes())
    {
        myString = setNode.Descendants("title").First()....
    }

From First(), how do i get the inner value of the title node? (in this case it would be "hello1")

Calling ToString() on the element yields "hello1", which obviously isn't quite what I want

Upvotes: 2

Views: 171

Answers (2)

Ty.
Ty.

Reputation: 3948

I know this was already answered and accepted, but I can't help but point out that you could be doing more with LINQ.

collectionXML
    .Elements("sets")
    .Elements("set")
    .Select(c => c)
    .Each(x => SetValue(x));

void SetValue(XElement element)
{
    myString = element.GetElementValue("title");
}

// Each extension method (needs to be in a static class)
public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
    foreach (var item in items) action(item);
}

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064254

myString = setNode.Descendants("title").First().Value;

(however, I'm very vague as to what the initial DescendantNodes is doing; I'd tend to be a bit more particular about which nodes I am selecting)

Upvotes: 4

Related Questions