开发者

How To Save The String Variable Data To Xml File [closed]

It's difficult to 开发者_StackOverflow中文版tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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);


  1. 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);
        }
    }
    
  2. XDocument

    var document = new XDocument();
    document.Add(new XElement("MyData", (new XElement("MyField", "Test"))));
    document.Save(@"C:\test.xml");
    
  3. 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, use XDocument 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


  1. XmlWriter
  2. XDocument
  3. XmlDocument
  4. Serializer (XmlSerializer or DataContractSerializer)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜