私は通常、(逆)シリアル化を使用します。以前は問題はありませんでしたが、それは私が見ていない人間の間違いだと思います...シリアライゼーションは完璧に機能しますが、デシリアライゼーションは機能しません。
ここに私のコード:
using System;
using System.IO;
using System.Windows.Forms;
using Utils;
using System.Xml;
using System.Xml.Serialization;
namespace Tests
{
public partial class MainForm : Form
{
private Test test;
public MainForm()
{
InitializeComponent();
}
private void SaveButton_Click(object sender, EventArgs e)
{
try
{
test = new Test();
test.MyInt = int.Parse(MyIntTextBox.Text);
test.MyStr = MyStrTextBox.Text;
test.Save();
MessageBox.Show("Serialized!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception caught", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadButton_Click(object sender, EventArgs e)
{
try
{
test = Test.Load();
MyIntTextBox.Text = test.MyInt.ToString();
MyStrTextBox.Text = test.MyStr;
MessageBox.Show("Deserialized!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception caught", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
[Serializable]
public class Test
{
public string MyStr { set; get; }
public int MyInt { set; get; }
public void Save()
{
using (StreamWriter sw = new StreamWriter("TestSerialized.xml"))
{
XmlSerializer xs = new XmlSerializer(typeof(Test));
xs.Serialize(sw, this);
sw.Flush();
}
}
static public Test Load()
{
Test obj = null;
using (StreamReader sr = new StreamReader("TestSerialized.xml"))
{
XmlSerializer xs = new XmlSerializer(typeof(Test));
if (!xs.CanDeserialize(XmlReader.Create(sr)))
throw new NotSupportedException(string.Format("The file <{0}> cannot be loaded.", "TestSerialized.xml"));
obj = (Test)xs.Deserialize(sr);
}
return (obj);
}
}
}
これは、Test クラスの各プロパティに 1 つずつ、2 つのボタン (保存用と読み込み用) の 2 つのテキスト ボックスを備えた基本的なフォームです。
ロードするファイルがあることを確認します ;)
次のようなジェネリック (デ) serliazer クラスを作成したい:
public class Serializer<T>
{
static public void Serialize(object obj, string path)
{
using (StreamWriter sw = new StreamWriter(path))
{
XmlSerializer xs = new XmlSerializer(typeof(T));
xs.Serialize(sw, obj);
sw.Flush();
}
}
static public T Dezerialize(string path)
{
T obj;
using (StreamReader sr = new StreamReader(path))
{
XmlSerializer xs = new XmlSerializer(typeof(T));
if (!xs.CanDeserialize(XmlReader.Create(sr)))
throw new NotSupportedException(string.Format("The file <{0}> cannot be loaded.", path));
obj = (T)xs.Deserialize(sr);
}
return (obj);
}
}
しかし、私は同じ問題を抱えています:逆シリアル化が機能しません...
編集:例外がキャッチされました:「XML ドキュメントにエラーが存在します (0, 0)」そして、デシリアライズしたい XML ドキュメント (XmlSerializer によって生成されます)
<?xml version="1.0" encoding="utf-8"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyStr>toto</MyStr>
<MyInt>45</MyInt>
</Test>
助けてくれてありがとう!