[英]Most elegant way to serialize an object with byte[] members to an XDocument?
I have a serialization utility that serializes an object to an XDocument. 我有一个序列化实用程序,可将对象序列化为XDocument。 It works quite well : 效果很好:
public static class SerializationUtil
{
public static T Deserialize<T>(XDocument doc)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (var reader = doc.Root.CreateReader())
{
return (T)xmlSerializer.Deserialize(reader);
}
}
public static XDocument Serialize<T>(T value)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
XDocument doc = new XDocument(z);
using (var writer = doc.CreateWriter())
{
xmlSerializer.Serialize(writer, value);
}
return doc;
}
Been using it quite happily and suddenly I get : 一直很开心地使用它,突然我得到:
There was an error generating the XML document.
The inner exception is : 内部异常是:
This XmlWriter does not support base64 encoded data.
Turns out that the XDocument.CreateWriter()
instance method gives you a writer of type System.Xml.XmlWellFormedWriter
, and that that writer can't write base64 encoded data (my object contains a byte[]). 事实证明, XDocument.CreateWriter()
实例方法为您提供了类型为System.Xml.XmlWellFormedWriter
编写器,并且该编写器无法编写base64编码的数据(我的对象包含byte [])。
MSDN doesn't even seem to mention this class - but I can't seem to create any other type of writer from XDocument
. MSDN甚至似乎都没有提到此类-但是我似乎无法从XDocument
创建任何其他类型的writer。
I could just serialize to a string, but i was trying to be clever and avoid using any hacks. 我可以序列化为字符串,但是我试图变得聪明,避免使用任何黑客手段。 Any way to serialize to XDocument when base64 is needed for certain fields. 当某些字段需要base64时,可以使用任何方式序列化到XDocument。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.