Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting author name field from Atom feed using LINQ (C#)

Tags:

c#

linq

atom-feed

I'm trying to select the "name" field from the author node in an ATOM feed using LINQ. I can get all the fields I need like so:

XDocument stories = XDocument.Parse(xmlContent);
XNamespace xmlns = "http://www.w3.org/2005/Atom";
var story = from entry in stories.Descendants(xmlns + "entry")
            select new Story
            {
                Title = entry.Element(xmlns + "title").Value,
                Content = entry.Element(xmlns + "content").Value
            };

How would I go about selecting the author -> name field in this scenario?

like image 382
Robert Dougan Avatar asked Nov 18 '08 22:11

Robert Dougan


2 Answers

You basically want:

entry.Element(xmlns + "author").Element(xmlns + "name").Value

But you might want to wrap that in an extra method so you can easily take appropriate action if either the author or name elements are missing. You might also want to think about what you want to happen if there's more than one author.

The feed might also have an author element... just another thing to bear in mind.

like image 144
Jon Skeet Avatar answered Oct 01 '22 03:10

Jon Skeet


It could be something like this:

        var story = from entry in stories.Descendants(xmlns + "entry")
                    from a in entry.Descendants(xmlns + "author")
                    select new Story
                    {
                        Title = entry.Element(xmlns + "title").Value,
                        Content = entry.Element(xmlns + "subtitle").Value,
                        Author = new AuthorInfo(
                            a.Element(xmlns + "name").Value,
                            a.Element(xmlns + "email").Value,
                            a.Element(xmlns + "uri").Value
                         )
                    };
like image 33
bruno conde Avatar answered Oct 01 '22 01:10

bruno conde