2008-11-18 49 views
5

我想从使用LINQ的ATOM提要中的作者节点中选择“姓名”字段。我能得到我需要像这样的所有字段:使用LINQ(C#)从Atom提要中选择作者姓名字段

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

我怎么会去选择的作者 - 在这种情况下>名称字段?

回答

5

你基本上要:

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

但你可能想包装在一个额外的方法,这样你可以很容易地采取适当的行动,如果无论是作者或名称的元素丢失。如果有多个作者,您可能还想考虑想要发生什么。

该提要可能还有一个作者元素......只是另一件需要牢记的事情。

+0

完美,谢谢! – 2008-11-19 10:02:10

3

这可能是这样的:

 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 
         ) 
        }; 
+0

我正在考虑使用某种嵌套的LINQ,但不知道如何去做。我会玩你的建议,欢呼! – 2008-11-19 10:00:52