Darren Young
Darren Young

Reputation: 11090

C# XML conversion

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,

Upvotes: 0

Views: 260

Answers (3)

Marcello Faga
Marcello Faga

Reputation: 1204

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

Upvotes: 2

Matthew Abbott
Matthew Abbott

Reputation: 61589

Could be as simple as

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

or

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

Upvotes: 4

Tomas Petricek
Tomas Petricek

Reputation: 243041

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).

Upvotes: 5

Related Questions