Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 525
Florian Greinacher Avatar asked Dec 06 '25 02:12

Florian Greinacher


2 Answers

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

gif example how it works

like image 111
ulex Avatar answered Dec 08 '25 16:12

ulex


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.

like image 32
George Mamaladze Avatar answered Dec 08 '25 17:12

George Mamaladze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!