2011-04-27 70 views
1

嘗試解析博客的RSS源時,我遇到了問題。雖然每個元素都進入我的課程,但包含實際內容的元素始終爲空。使用XDocument/XElement解析XML數據

<content:encoded>THIS IS FULL OF HTML </content:encoded>

那它似乎並沒有解析XML線。它也是唯一一個冒號,並且是唯一一個包含HTML數據的冒號。其他人看起來像這樣。

<title> 
An amazing Title 
</title> 
<link> 
More Junk 
</link> 
<comments> 
Comments and things 
</comments> 

我的代碼在下面,它讓每個其他元素都很好。有任何想法嗎?

allPosts = (from x in feed.Descendants("item") 
         select new blogPost 
         { 
          Creator = (string)x.Element("creator"), 
          Title = (string)x.Element("title"), 
          Published = DateTime.Parse((string)x.Element("pubDate")), 
          Content = (string)x.Element("content"), 
          Description = (string)x.Element("description"), 
          Link = (string)x.Element("link"), 
         }).ToList<blogPost>(); 

感謝

+0

你能指出我們在RSS提要嗎?此外,你可能想通過RSS驗證器來運行它,例如:http://www.rssboard.org/rss-validator/ – 2011-04-27 21:40:20

回答

1

看起來像你要找的內容,而不是用於編碼。內容是與編碼元素關聯的XML Namespace。你需要的是定義一個適當的XNamespace它並將其添加到您的查詢:

XNamespace contentNS = "<whatever the namespace is>"; 

allPosts = (from x in feed.Descendants("item") 
         select new blogPost 
         { 
          Creator = (string)x.Element("creator"), 
          Title = (string)x.Element("title"), 
          Published = DateTime.Parse((string)x.Element("pubDate")), 

          // Looking for content:encoded 
          Content = (string)x.Element(contentNS + "encoded"), 

          Description = (string)x.Element("description"), 
          Link = (string)x.Element("link"), 
         }).ToList<blogPost>(); 

contentNS的價值取決於什麼存在於你的原始XML,試圖尋找一個的xmlns:在內容定義根元素。

+0

我想通了。我遇到的問題是文件中的任何地方都沒有xmlns:content定義。我最終通過在線查看一些RSS文檔來找到它。爲什麼它不包含在我不確定的文件中。 – Woody 2011-04-28 13:27:43