How do I write an XML string to a file?

pragadheesh picture pragadheesh · Feb 26, 2009 · Viewed 99.8k times · Source

I have a string and its value is:

<ROOT>
    qwerty
    <SampleElement>adsf</SampleElement> 
    <SampleElement2>The text of the sample element2</SampleElement2> 
</ROOT>

How can I write this string to a file using C# 3.0?

Thanks in advance.

Answer

jvenema picture jvenema · Feb 26, 2009

Try this:

string s = "<xml><foo></foo></xml>";
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(s);
xdoc.Save("myfilename.xml");

Has the added benefit that the load will fail if your XML is invalid.