0

是否允许从 [Serializable] 属性类过渡到 IXmlSerializable 类并返回?以下代码按预期进行序列化,但它不会反序列化 A 的第二个属性(它始终返回 null)。

谢谢!

using System.Xml.Serialization;
using System.IO;
using System;

namespace Serialization
{
    [Serializable]
    public class A
    {
        public B B
        {
            get;
            set;
        }

        public string C
        {
            get;
            set;
        }
    }

    public class B : IXmlSerializable
    {
        private int _value;

        public void SetValue(int value)
        {
            _value = value;
        }

        public int GetValue()
        {
            return _value;
        }

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            int.TryParse(reader.ReadString(), out _value);
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            writer.WriteString(_value.ToString());
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            A a = new A() {B = new B(), C = "bar"};
            a.B.SetValue(1);

            XmlSerializer serializer = new XmlSerializer(typeof(A));
            Stream stream = File.Open("foo.xml", FileMode.Create);
            serializer.Serialize(stream, a);
            stream.Close();

            stream = File.Open("foo.xml", FileMode.Open);

            A a1 = serializer.Deserialize(stream) as A;

            if (a1.B.GetValue() != 1 || a1.C != "bar")
            {
                System.Diagnostics.Trace.WriteLine("Failed.");
            }
            else
            {
                System.Diagnostics.Trace.WriteLine("Succeeded.");
            }               
        }

    }
}

产生预期的 XML:

<?xml version="1.0"?>
<A xmlns:xsd="http://www.w3.org/2001/XMLSchema"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<B>1</B>
<C>bar</C>
</A>
4

1 回答 1

2

我最近遇到了同样的问题。我认为这是因为“reader.ReadString()”本身不会移动阅读光标。阅读完毕后,您需要移动它,例如

public void ReadXml(System.Xml.XmlReader reader)
{
    int.TryParse(reader.ReadString(), out _value);
    reader.Read();
}

或者你可以使用以下

public void ReadXml(System.Xml.XmlReader reader)
{
    _value = reader.ReadElementContentAsInt();
}

希望这可以解决您的问题。

于 2013-06-27T18:29:20.167 回答