2012-10-12 56 views
2

我正在創建一個程序,爲i​​Tunes Podcast編寫一個rss文件。我知道你可以買一個,但這是爲了經驗和非營利組織。這裏是我的C#代碼XmL文件,需要寫入「通道」元素的末尾

XDocument doc = XDocument.Load(fileLocation); 
     XNamespace itunes = "http://www.itunes.com/dtds/podcast-1.0.dtd"; 


     XElement root = new XElement("item", 
     (new XElement("title", textBoxPodcastTitle.Text)), 
     (new XElement(itunes + "author", textBoxAuthor.Text)), 
     (new XElement(itunes + "subtitle", textBoxSubtitle.Text)), 
     (new XElement(itunes + "summary", textBoxSummary.Text)), 
     (new XElement("enclosuer", 
        new XAttribute("url", "\"http://www.jubileespanish.org/Podcast/\"" + textBoxFileName.Text + "\"" + " length=\"" + o_currentMp3File.Length.ToString() + "\" type=\"audio/mpeg\""))), 
     (new XElement("guid", "http://www.jubileespanish.org/Podcast/" + textBoxFileName.Text)), 
     (new XElement("pubDate", o_selectedMP3.currentDate())), 
     (new XElement(itunes + "duration", o_selectedMP3.MP3Duration(openFileDialogFileName.FileName.ToString()))), 
     (new XElement("keywords", textBoxKeywords.Text))); 

     doc.Element("channel").Add(root); 
     doc.Save(fileLocation); 

一切工作正常,除非我寫我根XElement。它不能編寫它,因爲在iTunes頻道元素中除了「item」元素外還有其他元素(播客信息的其餘部分)。我怎樣才能將它追加到通道元素中,但恰好在結束標記之前。這裏是xml文件的樣子。謝謝,我是新溫柔......

<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0"> 
<channel> 
    <title>Non Profit company</title> 
    <itunes:keywords>keywords</itunes:keywords> 
    <itunes:image href="http://www.podcast.org/Podcast/podcastlogo.png" /> 
    <itunes:explicit>no</itunes:explicit> 
    <itunes:block>no</itunes:block> 


<item> 
    <title>Red, Whine, &amp; Blue</title> 
    <itunes:author>Various</itunes:author> 
    <itunes:subtitle>Red + Blue != Purple</itunes:subtitle> 
    <itunes:summary>This week we talk about surviving in a Red state if you are a Blue person. Or vice versa.</itunes:summary> 
    <itunes:image href="http://example.com/podcasts/everything/AllAboutEverything/Episode3.jpg" /> 
    <enclosure url="http://example.com/podcasts/everything/AllAboutEverythingEpisode1.mp3" length="4989537" type="audio/mpeg" /> 
    <guid>http://example.com/podcasts/archive/aae20050601.mp3</guid> 
    <pubDate>Wed, 1 Jun 2005 19:00:00 GMT</pubDate> 
    <itunes:duration>3:59</itunes:duration> 
    <itunes:keywords>politics, red, blue, state</itunes:keywords> 
</item> 

</channel> 
</rss> 

我想右

由於之前追加。

回答

1

這應該工作:

 doc.Root.Element("channel").Add(root); 

元素通過訪問Root屬性檢索是rssAdd方法將元素添加到默認情況下,元素的內容結束。

其他可能的方式來做到這一點是:

 doc.Element("rss").Element("channel").Add(root); 

或:

 var el = doc.Descendants("channel").FirstOrDefault(); 
     if (el != null) 
      el.Add(root); 

但第一個(使用Root屬性)將是最乾淨的。

+0

謝謝伊萬,我用你的第二個例子。它工作完美。 –

+0

不客氣,何塞,我很高興能夠幫到你。 –