2008-11-18 17 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