簡體   English   中英

XML序列化器序列化擴展列表的類

[英]XML Serializer serializing a Class that extend List

我有一個ac#項目,其中包含接口和擴展該接口的類。 顯然,Serializer不喜歡Interface,因此,我必須創建一個擴展List的集合類,這可以工作,但是我需要排除List根。 請在下面找到代碼示例

public interface ICreature

[XmlRoot("Creature")]
public class Man : ICreature

[XmlRoot("Creature")]
public class Alien : ICreature

public class CreatureCollection : List<ICreature>, IXmlSerializable
{
        public System.Xml.Schema.XmlSchema GetSchema() { return null; }

        public void ReadXml(XmlReader reader)
        {

        }

        public void WriteXml(XmlWriter writer)
        {
            foreach (ICreature aCreature in this)
            {
                XmlSerializer xmlSerializer = new XmlSerializer(aCreature.GetType());
                xmlSerializer.Serialize(writer, aCreature);
            }
        }
}

public class Something{
    ...
    public CreatureCollection{get;set;}
}


public void main(){
    Something sm = new Something();

    sm.CreatureCollection.Add(new Alien());
    sm.CreatureCollection.Add(new Man());
}

XML輸出:

<Something>
    <CreatureCollection>
        <Creature></Creature>
        <Creature></Creature>
    </CreatureCollection>
</Someting>

需要的輸出:

<Something>
        <Creature></Creature>
        <Creature></Creature>
</Someting>

請幫忙!...謝謝!

像這樣添加XmlElement

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

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            CreatureCollection creatures = new CreatureCollection() { creatures = new List<string>() { "", "", "" } };
            StringBuilder builder = new StringBuilder();
            StringWriter writer = new StringWriter(builder);
            XmlWriter xWriter = XmlWriter.Create(writer);
            creatures.WriteXml(xWriter);

        }
    }



    public class CreatureCollection : List<string>, IXmlSerializable
    {
        public List<string> creatures { get; set; }

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

        public void ReadXml(XmlReader reader)
        {

        }

        public void WriteXml(XmlWriter writer)
        {
            Something something = new Something() { creatures = new List<string>() };
            something.creatures.AddRange(creatures);

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(Something));
            xmlSerializer.Serialize(writer, something);
        }
    }
    [XmlRoot("Something")]
    public class Something
    {
        [XmlElement("Creature")]
        public List<string> creatures { get; set; }
    }


}
​

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM