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#.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With