using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace XmlTest
{
class TestClass : IXmlSerializable
{
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
var data = new byte[3];
reader.ReadStartElement();
reader.ReadElementContentAsBase64(data, 0, data.Length);
}
public void WriteXml(XmlWriter writer)
{
var data = new byte[] { 1, 2, 3 };
writer.WriteBase64(data, 0, data.Length);
}
public static void Main()
{
var serializer = new DataContractSerializer(typeof(TestClass));
var stringWriter = new StringWriter();
using (var writer = XmlWriter.Create(stringWriter))
{
serializer.WriteObject(writer, new TestClass());
}
var stringReader = new StringReader(stringWriter.ToString());
using (var reader = XmlReader.Create(stringReader))
{
serializer.ReadObject(reader, true);
}
}
}
}
ReadElementContentAsBase64
行抛出NotSupportedException
消息:
此XmlReader不支持ReadElementContentAsBase64方法。使用CanReadBinaryContent属性来查明读者是否实现它。
(我查了,CanReadBinaryContent返回true)
我正在使用Microsoft .NET 3.5框架实现。
什么可能导致这种情况?
注意:我故意将DataContractSerializer与IXmlSerializable混合使用。我意识到DataContractSerializer更常用的方法是让我的类成为[DataContract]。
编辑:我现在正在使用解决方法:
Convert.FromBase64String(reader.ReadElementContentAsString())
不过,我想知道为什么常规方法会失败。
答案 0 :(得分:7)
我也遇到过这个问题。由linq的doc.CreateReader()
创建的XmlReader未实现Base64解码。我首先保存到MemoryStream并从中创建一个XmlReader:
Stream s = new MemoryStream();
XmlSerializer serializer = new XmlSerializer(typeof(SerializableDocument));
document.Save(s);
s.Seek(0, SeekOrigin.Begin);
using (XmlReader newReader = XmlReader.Create(s))
{
SerializableDocument serializableDocument = (SerializableDocument)serializer.Deserialize(newReader);
// do stuff with it
}
答案 1 :(得分:3)
我把罗伯特的答案变成了扩展方法,享受!
public static T DeserializeWithBinaryData<T>(this XElement el)
{
var xDoc = el.ToXmlDocument();
using (var ms = new MemoryStream())
{
xDoc.Save(ms);
ms.Seek(0, SeekOrigin.Begin);
var serializer = new XmlSerializer(typeof (T));
return (T)serializer.Deserialize(ms);
}
}