How To Save The String Variable Data To Xml File [closed]
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);
XmlSerializer
public 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); } }
XDocument
var document = new XDocument(); document.Add(new XElement("MyData", (new XElement("MyField", "Test")))); document.Save(@"C:\test.xml");
XmlTextWriter
using (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.WriteText
as this will not validate XML and will not take care of escaping characters, for example&
,%
, etc. - try to avoid using
XmlDocument
, useXDocument
instead (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)
精彩评论