1

how to write content in an existing .xml file which is totally empty? I am creating a new file named newXML.xml and storing its path in a string as follows:

File.Create(Application.StartupPath + @"newXML.xml");   
string path=Application.StartupPath + @"newXML.xml";

now i have some xml data with xml tags and i want to store these datas into a string and write those datas into the new file that i have created with the name newXML.xml.

The data that i want to store in string is as follows...

<configuration>
<system.runtime.remoting>
<application name="Server">
     <client>
     </client>
</application>
</system.runtime.remoting>
</configuration>

How can i do this?

Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
Manish Jain
  • 1,197
  • 1
  • 11
  • 32
  • http://stackoverflow.com/questions/284324/what-is-the-best-way-to-build-xml-in-c-sharp-code/284331#284331 – G J Oct 13 '14 at 07:24
  • 2
    Dou you *have* to do it this way? Why not fill a `XDocument` and then save it with something like `xDocument.Save(Application.StartupPath + @"newXML.xml")`? http://msdn.microsoft.com/library/bb345830.aspx – Corak Oct 13 '14 at 07:25
  • I am in a learning period and i can not use xDocument . Is there anyway by which i can store all the information in a string? – Manish Jain Oct 13 '14 at 07:30
  • You could simply use [File.WriteAllText](http://msdn.microsoft.com/library/ms143376.aspx) with UTF8 encoding. This is one of the (easiest) ways to write strings into files. This is okay for learning, but later, if you work with "real" XML data, you should definitely use the [LINQ to XML](http://msdn.microsoft.com/library/bb387098.aspx) classes. – Corak Oct 13 '14 at 07:34
  • 1
    If you put the XML data into a string, you need to escape the quotation marks. Like `string xmlData = "";` -- see how inside the string the quotation marks `"` are escaped and are now `\"`. – Corak Oct 13 '14 at 07:40

1 Answers1

4

Take a look at the XDocument class.

XDocument xml = new XDocument(
    new XElement("configuration",
        new XElement("system.runtime.remoting",
            new XElement("application",
                new XAttribute("name", "Server"),
                new XElement("client")))));
xml.Save(//Stream to save file);
Max Hampton
  • 1,254
  • 9
  • 20