2

我似乎能够在网上找到试图避免这种行为的人,但我似乎无法获得我想要的行为。

我有一个动物列表,我想为每种动物类型使用不同的标签对它们进行序列化(与带有附加属性的默认行为相反)

为了获得这种行为,我使用以下代码

    [XmlElementAttribute(Order = 4)]
    [XmlElement("Frog", typeof(Frog))]
    [XmlElement("Cat", typeof(Cat))]
    [XmlElement("Dog", typeof(Dog))]
    public List<Animal> lines = new List<Animal>();

效果很好,除了它会使列表变平,如果 xml 输出更像保留标签,我更 <animals> <Dog>Bob</Dog> <Cat>Fred</Cat> <Dog>Mike</Dog> </animals> 喜欢<animals>

4

2 回答 2

2

更改[XmlElementAttribute(Order = 4)][XmlArrayAttribute(Order=4)]

您还可以ElementName在属性中指定一个参数,该参数将是根名称,即:[XmlArrayAttribute(Order=4, ElementName="animals")]

*注意:Order=4 是针对这种情况的。你通常不需要它。*

编辑:(感谢OP评论):

您还必须将属于列表的对象的类的属性从更改[XmlElement][XmlArrayItem] (MSDN doc here),如下所示:

[XmlArrayItem("Frog", typeof(Frog))]
[XmlArrayItem("Cat", typeof(Cat))]
[XmlArrayItem("Dog", typeof(Dog))]
于 2012-05-09T23:25:47.120 回答
0

您始终可以将列表包装在其自己的类中,并且您将获得您期望的 XML:

public class StackOverflow_10524470
{
    public class Animal
    {
        [XmlText]
        public string Name { get; set; }
    }
    public class Dog : Animal { }
    public class Cat : Animal { }
    public class Frog : Animal { }
    public class Root
    {
        [XmlElementAttribute(Order = 4, ElementName = "animals")]
        public Animals animals;
    }
    public class Animals
    {
        [XmlElementAttribute(Order = 4)]
        [XmlElement("Frog", typeof(Frog))]
        [XmlElement("Cat", typeof(Cat))]
        [XmlElement("Dog", typeof(Dog))]
        public List<Animal> lines = new List<Animal>();
    }
    public static void Test()
    {
        MemoryStream ms = new MemoryStream();
        XmlSerializer xs = new XmlSerializer(typeof(Root));
        Root root = new Root
        {
            animals = new Animals
            {
                lines = new List<Animal> 
                { 
                    new Dog { Name = "Fido" },
                    new Cat { Name = "Fluffy" },
                    new Frog { Name = "Singer" },
                }
            }
        };
        xs.Serialize(ms, root);
        Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
    }
}
于 2012-05-09T22:03:41.307 回答