سؤال

Is it allowable to transition from [Serializable] attribute classes to IXmlSerializable classes and back? The following code serializes as expected, but it does not deserialize the second property of A (it always returns null).

Thanks!

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.");
            }               
        }

    }
}

Produces the expected 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>
هل كانت مفيدة؟

المحلول

I had the same problem recently. I think it's because that "reader.ReadString()" doesn't move the reading cursor by itself. You need to move it after you are done reading, like with

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

Or you could use the following

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

Hopefully, that should fix your problem.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top