gpt4 book ai didi

.net - "ReadElementContentAsBase64 method is not supported on this XmlReader"

转载 作者:行者123 更新时间:2023-12-02 03:48:18 29 4
gpt4 key购买 nike

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 并显示消息:

ReadElementContentAsBase64 method is not supported on this XmlReader. Use CanReadBinaryContent property to find out if a reader implements it.

(我检查过,CanReadBinaryContent 返回 true)

我正在使用 Microsoft .NET 3.5 框架实现。

什么可能导致这种情况?

注意:我有意将 DataContractSerializer 与 IXmlSerialized 混合在一起。我意识到 DataContractSerializer 更常见的方法是将我的类设为 [DataContract]。

编辑:我现在正在使用解决方法:
Convert.FromBase64String(reader.ReadElementContentAsString())
不过,我想知道为什么常规方法会失败。

最佳答案

我也遇到这个问题了。 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
}

关于.net - "ReadElementContentAsBase64 method is not supported on this XmlReader",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3765550/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com