【问题标题】:Object xml serialization / deserialization对象xml序列化/反序列化
【发布时间】:2017-12-21 20:25:33
【问题描述】:

我在同一主题中找到了一些讨论,但仍然找不到以 xml 格式序列化/反序列化对象的非常简单任务的最终解决方案。

我遇到的问题是:

XML 文档中存在错误 (2,2)

以及重现问题的代码:

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

那么这里有什么问题呢?

【问题讨论】:

  • 能否提供xml,我想在我的最后尝试
  • 当然,这里是:w3.org/2001/XMLSchema-instance" xmlns:xsd="w3.org/2001/XMLSchema "> 10sssdf
  • 不完全是,我猜想该帖子中根本没有提到的命名空间有问题。

标签: c# xml serialization


【解决方案1】:

您使用错误的类型调用反序列化。

这将为您构建一个序列化程序以从 XML 返回一个对象。

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

要让上面的行不吠叫,它的 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" />

如果您想返回 testclass,请告诉序列化程序这样做:

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

这将为您提供带有 xml 输入的 testclass 实例(如果我修复了其中的错误)

【讨论】:

  • 谢谢您,您说的完全正确,但是我对解决方案有疑问,因为我通常不知道要反序列化什么对象类型。我还需要保存对象类型名称并在反序列化之前使用反射来获取类型。真烦人……
  • 是的,你必须知道类型,但你可以在 xml 中查看第一个节点名以猜测类型。虽然仍然是一个猜测......
  • 这只是类型名称,我仍然需要反射来获取类型。但是没有问题,已经在这样工作了:-)
猜你喜欢
  • 2020-10-31
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 1970-01-01
  • 2013-03-24
  • 2018-10-11
  • 2012-04-15
相关资源
最近更新 更多