我試圖序列化並反序列化一個對象。序列化工作正常,但反序列化拋出一個對對象進行序列化和反序列化(XML文檔(0,0)中存在錯誤。)
System.InvalidOperationException : There is an error in XML document (1, 1).
----> System.Xml.XmlException : Data at the root level is invalid. Line 1, position 1.
序列化的XML看起來不錯:
<?xml version="1.0" encoding="utf-16"?>
<Data xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Id="1" Status="OK" xmlns="http://biz.si/Project/v0100/Data.xsd">
<DataGroup Type="SomeType">AAEC</DataGroup>
</Data>
編碼是UTF-16,這是確定的,但我懷疑有反序列化過程中的編碼問題。現在代碼在測試環境(單元測試)中運行,但序列化的XML將被髮送到Web服務。
這是我的代碼:
[TestFixture]
public class Foobar
{
[Test]
public void Test()
{
var d = new Data
{
Id = "1",
Status = "OK",
DataGroup = new DataGroup
{
Type = "SomeType",
Value = new byte[] { 0x00, 0x01, 0x02 }
}
};
var serialized = Serialize(d);
var deserialized = Deserialize(serialized); // exception is thrown here.
Debug.WriteLine("ok");
}
private XmlNode Serialize(Data data)
{
XmlSerializer xsSubmit = new XmlSerializer(typeof(Data));
StringWriter sww = new StringWriter();
using (XmlWriter writer = XmlWriter.Create(sww))
{
xsSubmit.Serialize(writer, data);
var xml = sww.ToString();
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
return xmlDocument;
}
}
private Data Deserialize(XmlNode xmlData)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Data));
MemoryStream memoryStream = new MemoryStream(Encoding.Default.GetBytes(xmlData.InnerText));
return (Data)xmlSerializer.Deserialize(memoryStream);
}
}
[XmlRoot(Namespace = "http://biz.si/Project/v0100/Data.xsd", IsNullable = false)]
[XmlType(AnonymousType = true)]
public class Data
{
[XmlAttribute]
public string Id { get; set; }
[XmlAttribute]
public string Status { get; set; }
[XmlElement("DataGroup")]
public DataGroup DataGroup { get; set; }
}
[XmlType(AnonymousType = true)]
public class DataGroup
{
[XmlAttribute]
public string Type { get; set; }
[XmlText(DataType = "base64Binary")]
public byte[] Value { get; set; }
}
沒有定義的構造A C#類都有一個默認構造函數,它是無參數(授予有趣的情況下的基類沒有公共參數構造函數)。這就是爲什麼他「似乎能夠」序列化一個「似乎」沒有無參數構造函數的類。注意他的'Test()'方法創建了一個沒有任何構造函數參數的'Data' *實例:'var d = new Data {};'。這是一個無參數的構造函數。 –
謝謝你的信息埃德!我喜歡學習新事物。 – DB9