I am trying to serialize and then deserialize an object. Serialization works ok, but deserialization throws a
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 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>
[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; }
}
Two problems here: InnerText
is not the property you want. It's not XML at all; look at it in the debugger. Second, don't use MemoryStream
; wherever you got that one, he was just trolling you. StringReader
is much easier to get working.
private Data Deserialize(XmlNode xmlData)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Data));
using (var stream = new StringReader(xmlData.OuterXml))
{
return (Data)xmlSerializer.Deserialize(stream);
}
}