使用Bond throws反序列化xml System.IO.InvalidDataException:意外的节点类型

时间:2015-08-13 12:49:09

标签: c# xml bond

我使用以下代码与Bond玩了一点:

using System;
using System.IO;
using System.Text;
using System.Xml;
using Bond;
using Bond.Protocols;
using NUnit.Framework;

public class Sandbox
{
    [Test]
    public void RoundtripWithSchema()
    {
        var sb = new StringBuilder();
        var source = new WithSchema { Value = 1 };

        using (XmlWriter xmlWriter = XmlWriter.Create(sb))
        {
            var writer = new SimpleXmlWriter(xmlWriter);
            Serialize.To(writer, source);
        }
        var xml = sb.ToString();
        Console.Write(xml);
        Console.WriteLine();

        using (var xmlReader = XmlReader.Create(new StringReader(xml)))
        {
            var reader = new SimpleXmlReader(xmlReader);
            var roundtripped = Deserialize<WithSchema>.From(reader); // System.IO.InvalidDataException : Unexpected node type
            Assert.AreEqual(source.Value, roundtripped.Value);
        }
    }

    [Test]
    public void RoundtripUsingSerializerWithSchema()
    {
        var sb = new StringBuilder();
        var source = new WithSchema { Value = 1 };

        using (XmlWriter xmlWriter = XmlWriter.Create(sb))
        {
            var writer = new SimpleXmlWriter(xmlWriter);
            var serializer = new Serializer<SimpleXmlWriter>(typeof(WithSchema));
            serializer.Serialize(source, writer);
        }
        var xml = sb.ToString();
        Console.Write(xml);
        Console.WriteLine();

        using (var xmlReader = XmlReader.Create(new StringReader(xml)))
        {
            var reader = new SimpleXmlReader(xmlReader);
            var serializer = new Deserializer<SimpleXmlReader>(typeof(WithSchema));
            var roundtripped = serializer.Deserialize<WithSchema>(reader); // System.IO.InvalidDataException : Unexpected node type
            Assert.AreEqual(source.Value, roundtripped.Value);
        }
    }
}

[Schema]
public class WithSchema
{
    [Id(0)]
    public int Value { get; set; }
}

两个样本都输出预期的xml:

<?xml version="1.0" encoding="utf-16"?>
<WithSchema>
    <Value>1</Value>
</WithSchema>

反序列化抛出System.IO.InvalidDataException时都失败:意外的节点类型

真的不知道在哪里找bug,建议?

1 个答案:

答案 0 :(得分:1)

债券SimpleXmlReader<?xml version="1.0" encoding="utf-16"?>行遇到问题。如果在序列化时将其删除,则可以顺利地反序列化。

尝试这样的事情

using (XmlWriter xmlWriter = XmlWriter.Create(sb, new XmlWriterSettings { OmitXmlDeclaration = true }))
{
    var writer = new SimpleXmlWriter(xmlWriter);
    Serialize.To(writer, source);
}

我的猜测是XmlNodeType.XmlDeclaration可能需要添加到Bond SimpleXmlParser中设置的IgnoredTokens

v4.0.1之后的债券版本将解决此问题(GitHub上的债券问题#112)。

这个答案的灵感来自Bond simple_xml sample