locked
Dynamically creating XML file and store data in it. RRS feed

  • Question

  • Hi,

    I am developing metro style app, here I need to create XML file dynamically and store data in it. Can anybody tell me the C# code to create XML file dynamically and code to store data in XML file.

    Thanks

    Megha


    • Edited by Megha.A Tuesday, March 27, 2012 10:39 AM
    Tuesday, March 27, 2012 10:28 AM

Answers

  • There are a lot of ways of doing it, I prefer LINQ to XML, here's a very simple example:

    var elements = new XElement("People",
                       new XElement("Person",
                            new XElement("Name","Mike"),
                            new XElement("Age","22")),
                       new XElement("Person",
                            new XElement("Name","Alice"),
                            new XElement("Age","45")));
    
    var document = new XDocument(elements);
    

    the output of this code will be:

    <People>
      <Person>
        <Name>Mike</Name>
        <Age>22</Age>
      </Person>
      <Person>
        <Name>Alice</Name>
        <Age>45</Age>
      </Person>
    </People>


    -Soroush

    • Marked as answer by Min ZhuMember Monday, April 2, 2012 5:49 AM
    Tuesday, March 27, 2012 10:50 AM
  • check out this page if you need more samples on LINQ to XML:

    http://msdn.microsoft.com/en-us/vstudio/bb688087

    Also if you don't want to use LINQ, you can use XmlWriter


    -Soroush


    Tuesday, March 27, 2012 10:54 AM

All replies

  • There are a lot of ways of doing it, I prefer LINQ to XML, here's a very simple example:

    var elements = new XElement("People",
                       new XElement("Person",
                            new XElement("Name","Mike"),
                            new XElement("Age","22")),
                       new XElement("Person",
                            new XElement("Name","Alice"),
                            new XElement("Age","45")));
    
    var document = new XDocument(elements);
    

    the output of this code will be:

    <People>
      <Person>
        <Name>Mike</Name>
        <Age>22</Age>
      </Person>
      <Person>
        <Name>Alice</Name>
        <Age>45</Age>
      </Person>
    </People>


    -Soroush

    • Marked as answer by Min ZhuMember Monday, April 2, 2012 5:49 AM
    Tuesday, March 27, 2012 10:50 AM
  • check out this page if you need more samples on LINQ to XML:

    http://msdn.microsoft.com/en-us/vstudio/bb688087

    Also if you don't want to use LINQ, you can use XmlWriter


    -Soroush


    Tuesday, March 27, 2012 10:54 AM