tags:

views:

60

answers:

2

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

+4  A: 
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)

Marc Gravell
How did I miss this?! Thanks
qui
You can also cast an XElement to a string instead of accessing its Value property. This can help avoid null reference errors in situations where the XElement reference might be null. For example, if the "title" node might or might not be present, you could do: (string)setNode.Descendants("title").FirstOrDefault()
Joel Mueller
A: 

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);
}
Ty