2012-09-05 83 views
3

有沒有什麼辦法從給定的XML字符串中生成C#中的XElement表示?從XML字符串生成XElement代碼

基本上我想要實現的是從一個字符串這樣的打算:

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<rss version="2.0"> 
    <channel> 
    <title>RSS Channel Title</title> 
    <description>RSS Channel Description.</description> 
    <link>http://aspiring-technology.com</link> 
    <item> 
     <title>First article title</title> 
     <description>First Article Description</description> 
    </item> 
    </channel> 
</rss> 

像這樣的字符串:

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"), 
    new XElement("rss", 
     new XAttribute("version", "2.0"), 
     new XElement ("channel", 
      new XElement("title", "RSS Channel Title"), 
      new XElement("description", "RSS Channel Description."), 
      new XElement("link", "http://aspiring-technology.com"), 
      new XElement("item", 
       new XElement("title", "First article title"), 
       new XElement("description", "First Article Description") 
      ) 
     ) 
    ); 

真的很感激任何提示!

+0

據我所知你正試圖建立一個代碼生成器。您可能會提及關鍵字「代碼生成」以避免誤導性答案。 –

回答

1

看看這個XElement/XDocument Code Generator。 它使用XSLT轉換從XML生成c#代碼。 如果我自己做,我可能會以同樣的方式做。

+0

這似乎是非常接近想要我想實現的。非常感謝! –

3

ReSharper 2016.1有一個上下文動作來將字符串轉換爲XElement或XDocument對象。

gif example how it works

+0

請添加描述性的視圖 - 你必須把「!」在線前。 – danopz