简体   繁体   English

对象xml序列化/反序列化

[英]Object xml serialization / deserialization

I found some discussion in same topic but still can't find the ultimate solution to a very simple task of serialize/deserialze an object in xml format. 我在同一主题中找到了一些讨论,但仍然找不到针对以xml格式序列化/反序列化对象的非常简单任务的最终解决方案。

The issue I run into is : 我遇到的问题是:

There is an error in XML document (2,2) XML文档(2,2)中有错误

在此处输入图片说明

And the code to reproduce issue : 和代码重现问题:

  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void Serialize_Click(object sender, EventArgs e)
    {
      testclass t = new testclass();
      t.dummyInt = 10;
      t.dummyString = "sssdf";
      textBox1.Text = t.SerializeObject();
    }

    private void Deserialize_Click(object sender, EventArgs e)
    {
      try
      {
        object o = MySerializer.DeserializeObject<object>(textBox1.Text);
      }
      catch (Exception Ex)
      {
        MessageBox.Show(Ex.Message + Ex.InnerException, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }
  }

public class testclass
{
  public int dummyInt;
  public string dummyString;
  public testclass() { }
}

public static class MySerializer
{
  public static string SerializeObject<T>(this T toSerialize)
  {
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
    using (StringWriter textWriter = new StringWriter())
    {
      xmlSerializer.Serialize(textWriter, toSerialize);
      return textWriter.ToString();
    }
  }

  public static T DeserializeObject<T>(string data)
  {
    XmlSerializer serializer = new XmlSerializer(typeof(T));

    using (StringReader sReader = new StringReader(data))
    {
      return (T)serializer.Deserialize(sReader);
    }
  }
}

So what is wrong here? 那么,这里出了什么问题?

You are calling Deserialize with the wrong type. 您正在使用错误的类型调用反序列化。

This will build you a serializer to return an object from XML. 这将为您构建一个序列化器,以从XML返回对象。

var o = MySerializer.DeserializeObject<object>(xml);

To have the above line not bark its xml input should look like: 要使上述行不吠叫,其xml输入应类似于:

<?xml version="1.0" encoding="utf-16"?>
<anyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

If you want to return a testclass tell the serializer to do so: 如果要返回测试testclass告诉序列化器这样做:

var tc = MySerializer.DeserializeObject<testclass>(xml);

That will give you a testclass instance with your xml input (if I fix the errors in it) 这将为您提供一个带有xml输入的testclass实例(如果我修复其中的错误)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM