how we can create new xml file by C# in the following situation:
- its winform.
- our xml code is in a string str = "<><><><>...etc"
now i want to create an xml file 开发者_JAVA技巧myxml.xml
which contains everything in str,
please answer in the context and thanks... need simple source code
XmlDocument.LoadXml
using System;
using System.Xml;
public class Sample {
public static void Main() {
// Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>"); //Your string here
// Save the document to a file and auto-indent the output.
XmlTextWriter writer = new XmlTextWriter("data.xml",null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
}
}
Hi how about creating a method just for this:
private static void CreateXMLFile(string xml, string filePath)
{
// Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml); //Your string here
// Save the document to a file and auto-indent the output.
XmlTextWriter writer = new XmlTextWriter(filePath, null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
}
If the only thing you want to do is to save the string as a file (and you don't want to do do XML-specific stuff like checking well-formedness or automatic indenting), you can simply use File.WriteAllText()
.
精彩评论