i am trying to develop a web application in c# but i want to ask that How do we save the string variable data to xml file ??
Hopes for your suggestions
Regards,
You can simply write all the text you want into a file using
File.WriteAllText
lets say your string is str...
File.WriteAllText("fileName.xml", str);
XmlSerializerpublic class Program { public class MyData { public string MyStringField { get; set; } public int MyIntField { get; set; } } public static void Main() { var data = new MyData { MyStringField = "Test", MyIntField = 1 }; var serializer = new XmlSerializer(typeof(MyData)); using (var stream = new StreamWriter("C:\\test.xml")) serializer.Serialize(stream, data); } }XDocumentvar document = new XDocument(); document.Add(new XElement("MyData", (new XElement("MyField", "Test")))); document.Save(@"C:\test.xml");XmlTextWriterusing (var xmlTextWriter = new XmlTextWriter(@"C:\test.xml", Encoding.UTF8)) { xmlTextWriter.WriteStartElement("MyData"); xmlTextWriter.WriteStartElement("MyStringField"); xmlTextWriter.WriteString("Test"); xmlTextWriter.WriteEndElement(); xmlTextWriter.WriteEndElement(); }
Notes:
- try to avoid writing XML as just
File.WriteTextas this will not validate XML and will not take care of escaping characters, for example&,%, etc. - try to avoid using
XmlDocument, useXDocumentinstead (assuming .NET 3.5 or higher).
try this:
protected void Button1_Click(object sender, EventArgs e)
{
using (StreamWriter fsWrite = new StreamWriter(@"F:/info.xml"))
{
fsWrite.WriteLine("<ROOT>" +
"<SIGN>1155</SIGN>" +
"<MAXLOOP>23</MAXLOOP>" +
"<TOTTAL_REC>5645</TOTTAL_REC>" +
"<PART_EXPORT>retert</PART_EXPORT>" +
"<LEAVE_EXPORT>retr</LEAVE_EXPORT>" +
"<SAL_TDS_EXPORT>rter</SAL_TDS_EXPORT>" +
"<HR_DET_EXPORT>rete</HR_DET_EXPORT>" +
"<SELECTIONWISE>ertre</SELECTIONWISE>" +
"</ROOT>");
}
}
you can concatinate your string in this
and refer below site for other xml related options:
http://www.dotnettutorials.com/tutorials/xml/winform-xml-add-cs.aspx
- XmlWriter
- XDocument
- XmlDocument
- Serializer (XmlSerializer or DataContractSerializer)
加载中,请稍侯......
精彩评论