Syneryx
Syneryx

Reputation: 1288

XDocument Descendants and Element always return null values

Hey all i have looked thoroughly through all the questions containing XDocument and while they are all giving an answer to what I'm looking for (mostly namespaces issues) it seems it just won't work for me.

The problem I'm having is that I'm unable to select any value, be it an attribute or element.

Using this XML

I'm trying to retrieve the speaker's fullname.

    public void GetEvent()
    {
        var xdocument = XDocument.Load(@"Shared\techdays2013.xml");
        XNamespace xmlns = "http://www.w3.org/2001/XMLSchema-instance";

        var data = from c in xdocument.Descendants(xmlns + "speaker")
                   select c.Element(xmlns + "fullname").Value;
    }

Upvotes: 3

Views: 6301

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273464

1) You have to drop the namespace

2) You'll have to query more precisely. All your <speaker> elements inside <speakers> have a fullname but in the next section I spotted <speaker id="94" />

A simple fix (maybe not the best) :

//untested
var data = from c in xdocument.Root.Descendants("speakers").Descendants("speaker")
          select c.Element("fullname").Value;

You may want to specify the path more precise:

xdocument.Element("details").Element("tracks").Element("speakers").

Upvotes: 1

Ilya Ivanov
Ilya Ivanov

Reputation: 23636

You can omit WebClient because you have direct local access to a file. I'm just showing a way to process your file on my machine.

void Main()
{
    string p = @"http://events.feed.comportal.be/agenda.aspx?event=TechDays&year=2013&speakerlist=c%7CExperts";
    using (var client = new WebClient())
    {
        string str = client.DownloadString(p);
        var xml = XDocument.Parse(str);

        var result = xml.Descendants("speaker")
                        .Select(speaker => GetNameOrDefault(speaker));


        //LinqPad specific call        
        result.Dump();
    }
}
public static string GetNameOrDefault(XElement element)
{
    var name = element.Element("fullname");
    return name != null ? name.Value : "no name";
}

prints:

Bart De Smet 
Daniel Pearson 
Scott Schnoll 
Ilse Van Criekinge 
John Craddock 
Corey Hynes 
Bryon Surace 
Jeff Prosise 

Upvotes: 1

Jehof
Jehof

Reputation: 35544

You can omit the namespace declaration in your linq statement.

public void GetEvent()
{
    var xdocument = XDocument.Load(@"Shared\techdays2013.xml");
    //XNamespace xmlns = "http://www.w3.org/2001/XMLSchema-instance";

    var data = from c in xdocument.Descendants("speaker")
               select c.Element("fullname").Value;
}

Upvotes: 2

Related Questions