1

我使用以下代码与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:意外的节点类型

真的不知道在哪里寻找错误,建议?

4

1 回答 1

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可能需要添加到IgnoredTokensBond 的SimpleXmlParser中的集合中。

高于 v4.0.1 的 Bond 版本将修复此问题(GitHub 上的Bond issue #112 )。

此答案的灵感来自Bond simple_xml 示例

于 2015-12-10T07:20:21.850 回答