(Appendix to Steve Guidi's answer)
As far as I can see there is no implementation of XmlReader
you can easily use with XDocument
without moving the XML content through an intermediate store like a string representation of the XML and that supports all types that for example the System.Xml.XmlNodeReader
supports.
The reader returned by XDocument.CreateReader
(which is a System.Xml.Linq.XNodeReader
, an internal class) is a XmlReader
and works for most Xml document but not with documents that have binary data elements because its implementation does not support Base64 or BinHex data:
Base64 and BinHex data are not supported. If you attempt to retrieve
these types of data (for example, by calling
ReadElementContentAsBase64), the reader will throw
NotSupportedException.
For this reader XDocument.CreateReader().CanReadBinaryContent
is false
in contrast to the System.Xml.XmlNodeReader
.
For example this program throws an exception:
public class SomeTest
{
public byte[] BinaryTest { get; set; }
}
class Program
{
static void Main(string[] args)
{
XDocument document = new XDocument(
new XElement("SomeTest",
new XElement("BinaryTest", "VGVzdA==")));
using (var reader = document.CreateReader())
{
var serializer = new XmlSerializer(typeof(SomeTest));
var someTest = serializer.Deserialize(reader) as SomeTest;
// NotSupportedException here (as inner exception)
}
}
}
However, extracting the XML as string
and passing it as TextReader
into the serializer works:
using (var reader = new StringReader(document.ToString()))
I would be interested as well if there is another way to deserialize an XDocument
that includes binary data without converting it into a string first.