Search code examples
c#code-generationxelement

Generate XElement code from XML string


Is there any way to generate the XElement representation in C# from a given XML string?

Basically what I want to achieve is going from a string like this:

<?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>

To a string like this:

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")
           )
       )
    );

Really appreciate any hints!


Solution

  • Take a look at this XElement/XDocument Code Generator. It generates c# code from XML using XSLT transformation. If I would do it myself I'll probably do it the same way.