Chat  

LINQ - Creazione XML

LINQ - Creazione XML

PDFStampaE-mail

Creare un file XML con LINQ è una operazione molto semplice:

utilizzando il namespace  System.Xml.Linq:

 

XElement xml = new XElement("contacts",
                    new XElement("contact", 
                        new XAttribute("contactId", "2"),
                        new XElement("firstName", "Barry"),
                        new XElement("lastName", "Gottshall")
                    ),
                    new XElement("contact", 
                        new XAttribute("contactId", "3"),
                        new XElement("firstName", "Armando"),
                        new XElement("lastName", "Valdes")
                    )
                );
 
 
Console.WriteLine(xml);

Il risultato è:

<contacts>
  <contact contactId="2">
    <firstName>Barry</firstName>
    <lastName>Gottshall</lastName>
  </contact>
  <contact contactId="3">
    <firstName>Armando</firstName>
    <lastName>Valdes</lastName>
  </contact>
</contacts>


un esempio estremamente completo è il seguente:

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XComment("Sample RSS Feed"),
    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"),
                new XElement("pubDate", DateTime.Now.ToUniversalTime()),
                new XElement("guid", Guid.NewGuid())),
            new XElement("item",
                new XElement("title", "Second article title"),
                new XElement("description", "Second Article Description"),
                new XElement("pubDate", DateTime.Now.ToUniversalTime()),
                new XElement("guid", Guid.NewGuid()))
            )
        )
     );


doc.Save(@"c:\sample.xml");


file:
<?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>
      <pubDate>2006-12-05T20:53:53.53125</pubDate>
      <guid>ff7bbf19-9155-4773-913c-767bcbf09904</guid>
    </item>
    <item>
      <title>Second article title</title>
      <description>Second Article Description</description>
      <pubDate>2006-12-05T20:53:53.5625</pubDate>
      <guid>8a3fd5e8-b99f-49fe-8a43-7fb62d80c18c</guid>
    </item>
  </channel>
</rss>

 

© 2018 - Andrea Facchin
   
| Domenica, 23. Settembre 2018 || Designed by: LernVid.com |