How to save this string into XML file?
I have this string variable:
string xml = @"<Contacts>
<Contact&g开发者_高级运维t;
<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#.
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);
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(yourXMLString);
xdoc.Save("myfilename.xml");
If you don't need to do any processing on the string (with an XML library, for example), you could just do:
File.WriteAllText(@"c:\myXml.xml", xml);
System.IO.File.WriteAllText("filename.xml", xml );
You can do this:
string path = @"C:\testfolder\testfile.txt";
using (System.IO.StreamWriter file = new System.IO.StreamWriter(path))
{
file.Write(text);
}
You can also do this after you've created an XML Document, but it is slower:
xdoc.Save
If you want to save the string as-is without performing any check on whether it's well-formed or valid, then as has been answered above, use System.IO.File.WriteAllText("C:\myfilename.xml", xml );
As has also been noted, this defaults to saving the file as UTF-8, but you can specify encoding as Jon Skeet mentioned.
I'd recommend adding an XML declaration to the string, e.g.,
<?xml version="1.0" encoding="UTF-8"?>
and ensuring the encoding in the declaration matches that in the WriteAllText method. It's likely to save a fair amount of hassle at later date, judging by the frequency of XML encoding questions on stackoverflow.
If you want to ensure the XML is well-formed and/or valid, then you will need to use an XML parser on it first, such as XDocument doc = XDocument.Parse(str);
That method is also overridden if you want to preserve whitespace: XDocument.Parse(str, LoadOptions.PreserveWhitespace)
You can then perform validation on it http://msdn.microsoft.com/en-us/library/bb340331.aspx
before saving to file: doc.Save("C:\myfilename.xml");
精彩评论