0

InvalidOperationException在尝试运行此代码时遇到了问题。

示例代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace XMLSerializationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Caravan c = new Caravan();
            c.WriteXML();
        }
    }

    [XmlRoot("caravan", Namespace="urn:caravan")]
    public class Caravan
    {
        [XmlElement("vehicle")]
        public Auto Vehicle;
        public Caravan()
        {
            Vehicle = new Car {
                Make = "Suzuki",
                Model = "Swift",
                Doors = 3
            };
        }

        public void WriteXML()
        {
            XmlSerializer xs = new XmlSerializer(typeof(Caravan));
            using (TextWriter tw = new StreamWriter(@"C:\caravan.xml"))
            {
                xs.Serialize(tw, this);
            }
        }
    }
    public abstract class Auto
    {
        public string Make;
        public string Model;
    }
    public class Car : Auto
    {
        public int Doors;
    }
    public class Truck : Auto
    {
        public int BedLength;
    }
}

内部异常

{“类型 XMLSerializationExample.Car 不是预期的。使用 XmlInclude 或 SoapInclude 属性指定静态未知的类型。”}

问题

如何修复此代码?还有什么我应该做的吗?

我在哪里放置以下内容?

[XmlInclude(typeof(Car))]
[XmlInclude(typeof(Truck))]

将属性放在AutoCaravan类之上不起作用。将类型直接添加到XmlSerializer下面的示例中也不起作用。

XmlSerializer xs = new XmlSerializer(typeof(Caravan), new Type[] {
    typeof(Car), typeof(Truck) });
4

1 回答 1

2

我无法真正解释为什么需要这样做,但除了添加XmlInclude属性之外,您还需要确保您的类指定了一些非空名称空间,因为您已经在根目录上指定了名称空间(可能是一个错误)。它不一定必须是相同的命名空间,但它必须是某种东西。它甚至可以是一个空字符串,但它不能是null(这显然是默认值)。

这可以很好地序列化:

[XmlRoot("caravan", Namespace="urn:caravan")]
public class Caravan
{
    [XmlElement("vehicle")]
    public Auto Vehicle;

    //...
}

[XmlInclude(typeof(Car))]
[XmlInclude(typeof(Truck))]
[XmlRoot("auto", Namespace="")] // this makes it work
public abstract class Auto
{
    [XmlElement("make")] // not absolutely necessary but for consistency
    public string Make;
    [XmlElement("model")]
    public string Model;
}
于 2012-04-19T21:57:26.160 回答