0

我是 .NET 环境的初学者。我有一个带有三个文本框和一个按钮的 Windows 应用程序。当用户单击按钮时,我希望所有文本框值都以 XML 格式序列化到文件中。我试过这样做,

    DialogResult dr = new DialogResult();
    private void button1_Click(object sender, EventArgs e)
    {
        AddCustomer customer = new AddCustomer();
        customer.textBox1.Text = textBox1.Text;
        customer.textBox2.Text = textBox2.Text;
        customer.textBox3.Text = textBox3.Text;
        customer.textBox4.Text = textBox4.Text;

            saveFileDialog1.InitialDirectory = @"D:";
            saveFileDialog1.Filter = "Xml Files | *.xml";
            if (saveFileDialog1.ShowDialog().Equals(DialogResult.OK))
            {

                SerializeToXML(customer);
            }            
    }

    public void SerializeToXML(AddCustomer customer)
    {

           XmlSerializer serializer = new XmlSerializer(typeof(AddCustomer));
            TextWriter textWriter = new StreamWriter(@"D:\customer.xml");
            serializer.Serialize(textWriter, customer);
            textWriter.Close();
    }

这个返回的 system.invalidoperationexception 是未处理的异常

有任何想法吗?谢谢,迈克尔

4

3 回答 3

1

您不能序列化控件,而是必须创建Serializable表示 TextBox 值的组件。(有关更多详细信息,请阅读MSDN文章)。

例如,

[Serializable]
public class Customer
{
    public string Name { get; set; }
    public string Address {get;set;}
}
于 2011-12-26T03:04:29.007 回答
1

您不应该序列化文本框对象,只应该序列化它们的值。 customer.textBox1应该是customer.text1字符串类型。然后,您只需分配customer.text1 = textbox1.text. 另外,用属性标记你的AddCustomer类。[Serializable]

编辑:这是我刚刚尝试过的代码,它工作正常。看看你是否可以让它在你的解决方案中工作。

添加新班级Customer

[Serializable]
public class Customer
{
    public string FullName { get; set; }
    public string Age { get; set; }
}

尝试像这样序列化它

Customer customer = new Customer();
customer.FullName = "John"; // or customer.FullName = textBox1.Text
customer.Age = "21"; // or customer.Age = textBox2.Text

XmlSerializer serializer = new XmlSerializer(typeof(Customer));
TextWriter textWriter = new StreamWriter(@"D:\customer.xml");
serializer.Serialize(textWriter, customer);
textWriter.Close();

完成此操作后,我得到了一个使用以下内容创建的 xml 文件。

<?xml version="1.0" encoding="utf-8"?>
<Customer xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <FullName>John</FullName>
  <Age>21</Age>
</Customer>

试着比较一下,看看你做错了什么。

于 2011-12-26T03:07:05.163 回答
0

有很多方法可以在 .NET 中编写 XML。这是一种XmlWriter适用于非常简单的内容的方法,例如在这种情况下:

string text1 = /* get value of textbox */;
string text2 = /* get value of textbox */;
string text3 = /* get value of textbox */;

// Set indent=true so resulting file is more 'human-readable'
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };

// Put writer in using scope; after end of scope, file is automatically saved.
using (XmlWriter writer = XmlTextWriter.Create("file.xml", settings))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("root");
    writer.WriteElementString("text1", text1);
    writer.WriteElementString("text2", text2);
    writer.WriteElementString("text3", text3);
    writer.WriteEndElement();
}

注意:您应该避免在 UI 线程上执行文件操作,因为这可能会导致阻塞行为(例如,磁盘可能很慢并导致 UI 在写入文件时冻结,或者它可能正在写入网络位置并且在连接时挂起一段时间)。最好打开一个进度对话框并显示一条消息“请稍候,正在保存文件...”并在后台进行文件操作;一个简单的方法是使用BeginInvoke/EndInvoke将后台操作发布到线程池。


如果您想改用 XmlSerializer,那么您将按照以下步骤操作:

  1. 创建一个public类型作为文档的根元素,并用XmlRoot.
  2. 添加由原始/内置类型或您自己的public自定义类型组成的元素/属性,这些类型也是 XML 可序列化的,用XmlElementXmlAttribute根据需要标记它们。
  3. 要写出数据,请使用XmlSerializer.Serialize适当StreamStreamWriter, 或XmlWriter与您的根对象一起使用。
  4. 要读回数据,请使用XmlSerializer.Deseralize适当StreamTextReader、 或XmlReader,将返回类型转换回根对象。

完整样本。

要序列化的类型:

[XmlRoot("customer")]
public class CustomerData
{
    // Must have a parameterless public constructor
    public CustomerData()
    {
    }

    [XmlElement("name")]
    public string Name { get; set; }

    [XmlElement("city")]
    public string City { get; set; }

    [XmlElement("company")]
    public string Company { get; set; }

    public override string ToString()
    {
        return
            "Name=[" + this.Name + "] " +
            "City=[" + this.City + "] " +
            "Company=[" + this.Company + "]";
    }
}

读取/写入数据的代码:

// Initialize the serializer to write and read the data
XmlSerializer serializer = new XmlSerializer(typeof(CustomerData));

// Initialize the data to serialize
CustomerData dataToWrite = new CustomerData()
{
    Name = "Joel Spolsky",
    City = "New York",
    Company = "Fog Creek Software"
};

// Write it out
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
using (XmlWriter writer = XmlTextWriter.Create("customer.xml", settings))
{
    serializer.Serialize(writer, dataToWrite);
}

// Read it back in
CustomerData dataFromFile = null;
using (XmlReader reader = XmlTextReader.Create("customer.xml"))
{
    dataFromFile = (CustomerData)serializer.Deserialize(reader);
}

Console.WriteLine(dataFromFile);
于 2011-12-26T03:08:34.760 回答