Windows 窗体保存到 XML [英] Windows Form Save to XML

查看:28
本文介绍了Windows 窗体保存到 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,其中包含用户输入的信息,我想将其保存到 XML...我对编程相当陌生,但阅读过 XML 是最好的选择.我该怎么办?如果它有助于我使用 Sharp Develop 作为 IDE.目前它有 10 个文本框和 10 个日期时间选择器.

I have a form with information in it that the user enters, i want to save this to XML... i'm fairly new to programming but have read XML is the best thing to use. How would i go about it? If it helps im using Sharp Develop as an IDE. Current it has 10 text boxes and 10 datetimepickers.

推荐答案

最简单的方法是创建一个类,将这 10 个值存储为属性,并使用 xml 序列化将其转换为 XML,然后将其存储到文件系统.

The easiest thing would be to create a class that stores those 10 values as properties and use xml serialization to convert it to XML, then store it to the file system.

这里有一个教程:http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-序列化

更多细节:

这是超级基本的面向对象/Windows 窗体的东西.

This is super basic Object Oriented/Windows Forms stuff.

创建一个存储每个值的类:

Create a Class that stores each of the values:

public class Values{
    public string YourFirstValue { get; set;}
    public DateTime YourSecondValue { get; set;}
    ...
}

当然,您希望名称能够映射到它们的实际含义,但现在这些就足够了.

and of course you'd want names that map to their actual meanings, but these should suffice for now.

然后,当单击表单上的按钮时,将值存储在该类中:

Then, when clicking a button on your form, store the values in that class:

void Button1_OnClick(object sender, EventArgs args){
    Values v = new Values();
    v.YourFirstValue = this.FirstField.Text;
    v.YourSecondValue = this.YourSecondField.Value
    ...
    SaveValues(v);
}

然后使用 XmlSerializer 用于序列化和 StreamWriter 将结果存储到文件中.

Then implement the SaveValues method to serialize the xml using XmlSerializer for the serialization and StreamWriter to store the result to a file.

public void SaveValues(Values v){
    XmlSerializer serializer = new XmlSerializer(typeof(Values));
    using(TextWriter textWriter = new StreamWriter(@"C:TheFileYouWantToStore.xml")){
        serializer.Serialize(textWriter, movie);
    }
}

这篇关于Windows 窗体保存到 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆