您好,本人在做XML序列化的时候有这么一段:
public List<XMLSystemChild> GetChildren
        {
            get { return m_oChildren; }
            set { m_oChildren = value; }
        }
List中的泛型XMLSystemChild是一个基类,被好多个派生类继承,这样本人在输出XML序列化的时候遇到一个问题:
<XMLSystemChild xsi:type="XMLChild" ID="XMP_3" TagName="test5"> <Extent> <Max X="1" Y="1" Z="1" /> </Extent> <PersistentID /> <GenericAttributes Number="1" Set="test3"> <GenericAttribute Name="test2" Format="string" Value="2" /> </GenericAttributes> <XMLSystemChild xsi:type="XMLChildEx" ID="XMP_1" TagName="test"> <Extent> <Max X="1" Y="1" Z="1" /> </Extent> <PersistentID /> <GenericAttributes Number="1" Set="test3"> <GenericAttribute Name="test2" Format="string" Value="2" /> </GenericAttributes> </XMLSystemChild> </XMLSystemChild>
节点中多 有个属性xsi:type=”XMLChildEx” 说明派生类的类型。但是本人不希望这样,希望能为每个派生类制定单独的节点名称。问一下这个该怎么样做呢?
非常感谢您的解答!
解决方案
30
可以用XmlArrayItemAttribute:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
class Program
{
    static void Main()
    {
        My my = new My()
        {
            Name = "Minion",
            Pets = new List<Pet>() { new Dog(), new Cat() }
        };
        XmlSerializer serializer = new XmlSerializer(typeof(My));
        using (StringWriter sw = new StringWriter())
        {
            serializer.Serialize(sw, my);
            string xml = sw.ToString();
            /*
            <My xmlns:xsd="...">
              <Name>Minion</Name>
              <Pets>
                <Dog />
                <Cat />
              </Pets>
            </My>
            */
        }
    }
}
public class My
{
    public string Name { get; set; }
    [XmlArrayItem("Dog", Type = typeof(Dog))]
    [XmlArrayItem("Cat", Type = typeof(Cat))]
    public List<Pet> Pets { get; set; }
}
public class Pet { }
public class Dog : Pet { }
public class Cat : Pet { }
10
linq to  xml,读取成IEnumerable<XElement> 集合之后处理。
 
                    


