Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save this string into XML file?

Tags:

c#

xml

I have this string variable:

string xml = @"<Contacts>      <Contact>      <Name>Patrick Hines</Name>      <Phone Type=""Home"">206-555-0144</Phone>      <Phone Type=""Work"">425-555-0145</Phone>      <Phone Type=""Mobile"">332-899-5678</Phone>      <Address>          <Street1>123 Main St</Street1>          <City>Mercer Island</City>          <State>WA</State>          <Postal>68042</Postal>      </Address>      </Contact>      <Contact>      <Name>Dorothy Lee</Name>      <Phone Type=""Home"">910-555-1212</Phone>      <Phone Type=""Work"">336-555-0123</Phone>      <Phone Type=""Mobile"">336-555-0005</Phone>      <Address>          <Street1>16 Friar Duck Ln</Street1>          <City>Greensboro</City>          <State>NC</State>          <Postal>27410</Postal>      </Address>      </Contact> </Contacts>"; 

How can I save this string into an XML file in my drive c? Using c#.

like image 719
yonan2236 Avatar asked Jan 18 '11 08:01

yonan2236


People also ask

How do I save a string in XML?

If you have a valid string in "str", you can use XmlDocument to load the string and then save string to an XML file using Save method of XmlDocument. Don't forget to import System. Xml namespace before using XmlDocument.

How do I save something as XML?

Click File > Save As, and select the location where you want to save the file. , point to the arrow next to Save As, and then click Other Formats. In the File name box, type a name for the XML data file. In the Save as type list, click XML Data, and click Save.


1 Answers

The fact that it's XML is basically irrelevant. You can save any text to a file very simply with File.WriteAllText:

File.WriteAllText("foo.xml", xml); 

Note that you can also specify the encoding, which defaults to UTF-8. So for example, if you want to write a file in plain ASCII:

File.WriteAllText("foo.xml", xml, Encoding.ASCII); 
like image 111
Jon Skeet Avatar answered Oct 03 '22 22:10

Jon Skeet