XML序列化:反序列化抽象属性的问题

drk*_*str 0 .net c# xml-serialization

我仍然试图围绕整个xml序列化事物包围我的脑子,看起来我又需要一些帮助了.

我需要能够反序列化抽象类型的属性.这种类型将随着时间的推移而添加许多不同的具体类型,并且在许多不同的模型中被引用,因此明确列出每种具体类型并不是理想的解决方案.

我已经阅读了XML Serialization和Inherited Types线程,并提出了以下内容:

<Page>
  <introCommand>
    <PlayElement />
  </introCommand>
</Page>
Run Code Online (Sandbox Code Playgroud)

**

namespace TestService
{
    public class Page
    {
        [XmlElement("introCommand", Type = typeof(XmlCommandSerializer<AbstractCommandModel>))]
        //[XmlElement(typeof(PlayElement))] **NOTE: the example works if I use this instead
        public AbstractCommandModel introCommand;
    }
}
Run Code Online (Sandbox Code Playgroud)

**

namespace TestService
{
    public class AbstractCommandModel
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

**

namespace TestService
{
    public class PlayElement : AbstractCommandModel
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

**

namespace TestService
{
    public class XmlCommandSerializer<AbstractCommandModel> : IXmlSerializable
    {
        // Override the Implicit Conversions Since the XmlSerializer
        // Casts to/from the required types implicitly.
        public static implicit operator AbstractCommandModel(XmlCommandSerializer<AbstractCommandModel> o)
        {
            return o.Data;
        }

        public static implicit operator XmlCommandSerializer<AbstractCommandModel>(AbstractCommandModel o)
        {
            return o == null ? null : new XmlCommandSerializer<AbstractCommandModel>(o);
        }

        private AbstractCommandModel _data;
        /// <summary>
        /// [Concrete] Data to be stored/is stored as XML.
        /// </summary>
        public AbstractCommandModel Data
        {
            get { return _data; }
            set { _data = value; }
        }

        /// <summary>
        /// **DO NOT USE** This is only added to enable XML Serialization.
        /// </summary>
        /// <remarks>DO NOT USE THIS CONSTRUCTOR</remarks>
        public XmlCommandSerializer()
        {
            // Default Ctor (Required for Xml Serialization - DO NOT USE)
        }

        /// <summary>
        /// Initialises the Serializer to work with the given data.
        /// </summary>
        /// <param name="data">Concrete Object of the AbstractCommandModel Specified.</param>
        public XmlCommandSerializer(AbstractCommandModel data)
        {
            _data = data;
        }

        #region IXmlSerializable Members

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null; // this is fine as schema is unknown.
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            // Cast the Data back from the Abstract Type.
            string typeAttrib = reader.GetAttribute("type");

            // Ensure the Type was Specified
            if (typeAttrib == null)
                throw new ArgumentNullException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractCommandModel).Name +
                    "' because no 'type' attribute was specified in the XML.");

            Type type = Type.GetType(typeAttrib);

            // Check the Type is Found.
            if (type == null)
                throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractCommandModel).Name +
                    "' because the type specified in the XML was not found.");

            // Check the Type is a Subclass of the AbstractCommandModel.
            if (!type.IsSubclassOf(typeof(AbstractCommandModel)))
                throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractCommandModel).Name +
                    "' because the Type specified in the XML differs ('" + type.Name + "').");

            // Read the Data, Deserializing based on the (now known) concrete type.
            reader.ReadStartElement();
            this.Data = (AbstractCommandModel)new
                XmlSerializer(type).Deserialize(reader);
            reader.ReadEndElement();
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            // Write the Type Name to the XML Element as an Attrib and Serialize
            Type type = _data.GetType();

            // BugFix: Assembly must be FQN since Types can/are external to current.
            writer.WriteAttributeString("type", type.AssemblyQualifiedName);
            new XmlSerializer(type).Serialize(writer, _data);
        }

        #endregion
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我运行反序列化器时,我得到一个InvalidOperationException,指出"XML文档中存在错误(3,3)"..我在前面提到的线程中的例子中唯一改变的是类名.

我是否在正确的轨道上?如果是这样,我搞砸了什么导致这个错误?

csh*_*net 5

从你的例子:

//[XmlElement(typeof(PlayElement))] **NOTE: the example works if I use this instead
Run Code Online (Sandbox Code Playgroud)

这是支持抽象类的推荐方法.您可以按元素名称切换实例,并使用如下所示的多个声明:

[XmlElement("playElement", typeof(PlayElement))]
[XmlElement("testElement", typeof(TestElement))]
public AbstractCommandModel Command;
Run Code Online (Sandbox Code Playgroud)

当然,您仍然需要删除"introCommand"元素或添加另一个类来嵌套上述声明.

...

如果您仍然需要手动进行序列化,那么您就是正确的路径.您的示例运行良好我猜,这是XML输出:

<Page>
  <introCommand type="TestService.PlayElement, TestService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
    <PlayElement />
  </introCommand>
</Page>
Run Code Online (Sandbox Code Playgroud)

而这个xml读入你的对象就好了; 然而,这引起了安全问题.任何有权修改或将此XML注入您的应用程序的人都可以轻松注入代码.

以下用于测试您的示例代码:

    private static void Main()
    {
        StringWriter dataOut = new StringWriter();
        XmlTextWriter writer = new XmlTextWriter(dataOut);
        writer.Formatting = Formatting.Indented;

        Page p = new Page();
        p.introCommand = new PlayElement();

        new XmlSerializer(typeof(Page)).Serialize(writer, p);
        string xml = dataOut.ToString();
        Console.WriteLine(xml);

        XmlTextReader reader = new XmlTextReader(new StringReader(xml));
        Page copy = (Page) new XmlSerializer(typeof (Page)).Deserialize(reader);
    }
Run Code Online (Sandbox Code Playgroud)