Florian Greinacher
Florian Greinacher

Reputation: 14784

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!

Upvotes: 3

Views: 1001

Answers (2)

ulex
ulex

Reputation: 1287

ReSharper 2016.1 has a context action to convert string to XElement or XDocument object.

gif example how it works

Upvotes: 3

George Mamaladze
George Mamaladze

Reputation: 7931

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.

Upvotes: 1

Related Questions