tags:

views:

51

answers:

3

Hi,

I have a string containing fully formatted XML data, created using a Perl script.

I now want to convert this string into an actual XML file in C#. Is there anyway to do this?

Thanks,

+5  A: 

You can load a string into an in-memory representation, for example, using the LINQ to SQL XDocument type. Loading string can be done using Parse method and saving the document to a file is done using the Save method:

open System.Xml.Linq;

XDocument doc = XDocument.Parse(xmlContent);
doc.Save(fileName);

The question is why would you do that, if you already have correctly formatted XML document?
A good reasons that I can think of are:

  • To verify that the content is really valid XML
  • To generate XML with nice indentation and line breaks

If that's not what you need, then you should just write the data to a file (as others suggest).

Tomas Petricek
+4  A: 

Could be as simple as

File.WriteAllText(@"C:\Test.xml", "your-xml-string");

or

File.WriteAllText(@"C:\Test.xml", "your-xml-string", Encoding.UTF8);
Matthew Abbott
+2  A: 
XmlDocument doc = new XmlDocument();
doc.Load(... your string ...);
doc.Save(... your destination path...);

see also

http://msdn.microsoft.com/fr-fr/library/d5awd922%28v=VS.80%29.aspx

Marcello Faga