Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# XMl在C中序列化和反序列化多个派生类#_C#_Xmlserializer - Fatal编程技术网

C# XMl在C中序列化和反序列化多个派生类#

C# XMl在C中序列化和反序列化多个派生类#,c#,xmlserializer,C#,Xmlserializer,我试图按照Microsoft网站文档来解决上述问题。然而,我无法找到答案。因此,我尝试编写代码,但当我添加更多派生类时,我的对象没有被序列化 代码如下: using System; using System.IO; using System.Xml.Serialization; using System.Collections.Generic; public class Orchestra { // public Instrument[] Instruments; public

我试图按照Microsoft网站文档来解决上述问题。然而,我无法找到答案。因此,我尝试编写代码,但当我添加更多派生类时,我的对象没有被序列化

代码如下:

using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
public class Orchestra
{
    // public Instrument[] Instruments;
    public List<Instrument> Instruments;
    public int i;
    public float f;
    public string s1;
    public string s2;
    public B bc;
}
public class B
{
    public double dd;
}
public class Instrument
{
    public string Name;
}

public class Brass : Instrument
{
    public bool IsValved;
}
public class Percussion : Instrument
{
    public string name;
}
public class Run
{
    public static void Main()
    {
        Run test = new Run();
        test.SerializeObject("Override.xml");
        test.DeserializeObject("Override.xml");
    }

    public void SerializeObject(string filename)
    {
        /* Each overridden field, property, or type requires 
        an XmlAttributes object. */
        XmlAttributes attrs = new XmlAttributes();

        /* Create an XmlElementAttribute to override the 
        field that returns Instrument objects. The overridden field
        returns Brass objects instead. */
        XmlElementAttribute attr = new XmlElementAttribute();
        attr.ElementName = "Brass";
        attr.Type = typeof(Brass);

        attrs.XmlElements.Add(attr);
      //  attrs.XmlArrayItems.Add(attr);

       attr.ElementName = "Percussion";
        attr.Type = typeof(Percussion);
        // Add the element to the collection of elements.
        attrs.XmlElements.Add(attr);

        // Create the XmlAttributeOverrides object.
        XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();

        /* Add the type of the class that contains the overridden 
        member and the XmlAttributes to override it with to the 
        XmlAttributeOverrides object. */
        attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

        // Create the XmlSerializer using the XmlAttributeOverrides.
        XmlSerializer s =
        new XmlSerializer(typeof(Orchestra), attrOverrides);

        // Writing the file requires a TextWriter.
        TextWriter writer = new StreamWriter(filename);

        // Create the object that will be serialized.
        Orchestra band = new Orchestra();

        // Create an object of the derived type.
        //Brass i = new Brass();
        //i.Name = "Trumpet";
        //i.IsValved = true;
        //Instrument[] myInstruments = { i };
        //band.Instruments = myInstruments;
        List<Instrument> myInstruments = new List<Instrument>();
        myInstruments.Add(new Brass() { Name = "Trumpet", IsValved = true });
        myInstruments.Add(new Percussion() { Name = "Percussion", name = "Mridangam" });
        band.Instruments = myInstruments;
        band.i = 128;
        band.f = 5.678f;
        band.s1 = "Hi!";
        band.s2 = "GOOD!!!";
        B b = new B();
        b.dd = 2.35674848;
        band.bc = b;
        // Serialize the object.
        s.Serialize(writer, band);
        writer.Close();
    }

    public void DeserializeObject(string filename)
    {
        XmlAttributeOverrides attrOverrides =
           new XmlAttributeOverrides();
        XmlAttributes attrs = new XmlAttributes();

        // Create an XmlElementAttribute to override the Instrument.
        XmlElementAttribute attr = new XmlElementAttribute();
        attr.ElementName = "Brass";
        attr.Type = typeof(Brass);

        // Add the element to the collection of elements.
        attrs.XmlElements.Add(attr);

        attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

        // Create the XmlSerializer using the XmlAttributeOverrides.
        XmlSerializer s =
        new XmlSerializer(typeof(Orchestra), attrOverrides);

        FileStream fs = new FileStream(filename, FileMode.Open);
        Orchestra band = (Orchestra)s.Deserialize(fs);
        Console.WriteLine(band.i);
        Console.WriteLine(band.f);
        Console.WriteLine(band.s1);
        Console.WriteLine(band.s2);
        Console.WriteLine(band.bc.dd);
        Console.WriteLine("Brass:");

        /* The difference between deserializing the overridden 
        XML document and serializing it is this: To read the derived 
        object values, you must declare an object of the derived type 
        (Brass), and cast the Instrument instance to it. */
        //Brass b;
        //Percussion p;
        Brass b;
       // Percussion p;
        //b = (Brass)i;
       // int ii = 0;
        foreach (Instrument i in band.Instruments)
        //foreach(Instrument i in band.List<Instrument>)
        {
            //        int i = 0;
         //   ii++;
          //  if (ii == 1)
         //   {
                b = (Brass)i;
                Console.WriteLine(
                    b.Name + "\n" +
                    b.IsValved);
           // }
            /*if (ii == 2)
            {
                p = (Percussion)i;
                Console.WriteLine(
                    p.Name + "\n" +
                    p.name);

            }*/
        }
    }
}
使用系统;
使用System.IO;
使用System.Xml.Serialization;
使用System.Collections.Generic;
公共班管弦乐队
{
//公共文书[]文书;
公开清单文书;
公共国际一级;
公共基金;
公共字符串s1;
公共字符串s2;
公共B bc;
}
公共B级
{
公共双dd;
}
公共类文书
{
公共字符串名称;
}
公共级铜管乐器
{
公共图书馆关闭;
}
公开课打击乐器
{
公共字符串名称;
}
公营课
{
公共静态void Main()
{
运行测试=新运行();
序列化对象(“Override.xml”);
反序列化对象(“Override.xml”);
}
公共对象(字符串文件名)
{
/*每个重写的字段、属性或类型都需要
XmlAttributes对象*/
XmlAttributes attrs=新的XmlAttributes();
/*创建XmlElementAttribute以覆盖
返回仪表对象的字段。重写字段
而是返回黄铜对象*/
XmlElementAttribute attr=新的XmlElementAttribute();
attr.ElementName=“黄铜”;
属性类型=类型(黄铜);
attrs.xmlements.Add(attr);
//attrs.XmlArrayItems.Add(attr);
attr.ElementName=“打击乐器”;
属性类型=类型(打击);
//将元素添加到元素集合中。
attrs.xmlements.Add(attr);
//创建XmlAttributeOverrides对象。
XmlAttributeOverrides attrOverrides=新的XmlAttributeOverrides();
/*添加包含重写的类的类型
成员和要覆盖它的XmlAttributes
XmlAttributeOverrides对象*/
添加(类型(管弦乐队),“乐器”,属性);
//使用XmlAttributeOverrides创建XmlSerializer。
XmlSerializer s=
新的XmlSerializer(typeof(Orchestration),attrOverrides);
//写入文件需要一个TextWriter。
TextWriter writer=新的StreamWriter(文件名);
//创建将被序列化的对象。
管弦乐队=新管弦乐队();
//创建派生类型的对象。
//黄铜i=新黄铜();
//i、 Name=“喇叭”;
//i、 IsValved=真;
//文书[]myInstruments={i};
//波段仪器=我的仪器;
List myInstruments=新列表();
添加(newbrass(){Name=“喇叭口”,IsValved=true});
添加(新打击乐器(){Name=“打击乐器”,Name=“Mridangam”});
波段仪器=我的仪器;
波段i=128;
频带f=5.678f;
band.s1=“嗨!”;
band.s2=“好!!!”;
B=新的B();
b、 dd=2.35674848;
band.bc=b;
//序列化对象。
s、 连载(作家、乐队);
writer.Close();
}
public void反序列化对象(字符串文件名)
{
XmlAttributeOverrides属性覆盖=
新的XmlAttributeOverrides();
XmlAttributes attrs=新的XmlAttributes();
//创建XmlElementAttribute以覆盖该工具。
XmlElementAttribute attr=新的XmlElementAttribute();
attr.ElementName=“黄铜”;
属性类型=类型(黄铜);
//将元素添加到元素集合中。
attrs.xmlements.Add(attr);
添加(类型(管弦乐队),“乐器”,属性);
//使用XmlAttributeOverrides创建XmlSerializer。
XmlSerializer s=
新的XmlSerializer(typeof(Orchestration),attrOverrides);
FileStream fs=newfilestream(文件名,FileMode.Open);
管弦乐队=(管弦乐队)s.反序列化(fs);
控制台写入线(第一波段);
控制台写入线(f波段);
控制台写入线(带s1);
控制台写入线(带s2);
控制台写入线(band.bc.dd);
控制台。写线(“黄铜:”);
/*反序列化重写的
XML文档并序列化它是这样的:读取派生的
对象值,则必须声明派生类型的对象
(黄铜),并将仪器实例铸造到它上*/
//黄铜b;
//敲击p;
黄铜b;
//敲击p;
//b=(黄铜)i;
//int ii=0;
foreach(带内仪器i)
//foreach(仪器i带内列表)
{
//int i=0;
//ii++;
//如果(ii==1)
//   {
b=(黄铜)i;
控制台写入线(
b、 名称+“\n”+
b、 (带阀门);
// }
/*如果(ii==2)
{
p=(敲击)i;
控制台写入线(
p、 名称+“\n”+
p、 姓名);
}*/
}
}
}

我甚至尝试使用
XmlArrayItem
。谁能指导一下怎么做

您必须在代码中添加一个新类。见下面的代码:

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

public class Orchestras
{
    public List<Orchestra> orchestras = new List<Orchestra>();
}
public class Orchestra
{
    [XmlElement]
    public List<Instrument> Instruments { get; set; }
    public int i;
    public float f;
    public string s1;
    public string s2;
    public B bc;
}
public class B
{
    public double dd;
}
[XmlInclude(typeof(Brass))]
[XmlInclude(typeof(Percussion))]
public class Instrument
{
    public string Name;
}

public class Brass : Instrument
{
    public bool IsValved;
}
public class Percussion : Instrument
{
    public string name;
}
public class Run
{
    const string FILENAME = @"c:\temp\test.xml";
    public static void Main()
    {
        Run test = new Run();
        test.SerializeObject(FILENAME);
        test.DeserializeObject(FILENAME);
    }

    public void SerializeObject(string filename)
    {
        Orchestras orchastras = new Orchestras();
        Orchestra orchestra1 = new Orchestra();
        orchastras.orchestras.Add(orchestra1);
        List<Instrument> instruments = new List<Instrument>() { 
            new Instrument() { Name = "Brass"},
            new Instrument() { Name = "Percussion"}
        };

        orchestra1.Instruments = instruments;


        // Create the XmlSerializer using the XmlAttributeOverrides.
        XmlSerializer s = new XmlSerializer(typeof(Orchestras));


        // Writing the file requires a TextWriter.
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        XmlWriter writer = XmlWriter.Create(filename,settings);

        // Create the object that will be serialized.
        Orchestra band = new Orchestra();
        orchastras.orchestras.Add(band);
        // Create an object of the derived type.
        //Brass i = new Brass();
        //i.Name = "Trumpet";
        //i.IsValved = true;
        //Instrument[] myInstruments = { i };
        //band.Instruments = myInstruments;
        List<Instrument> myInstruments = new List<Instrument>();
        myInstruments.Add(new Brass() { Name = "Trumpet", IsValved = true });
        myInstruments.Add(new Percussion() { Name = "Percussion", name = "Mridangam" });
        band.Instruments = myInstruments;
        band.i = 128;
        band.f = 5.678f;
        band.s1 = "Hi!";
        band.s2 = "GOOD!!!";
        B b = new B();
        b.dd = 2.35674848;
        band.bc = b;
        // Serialize the object.
        s.Serialize(writer, orchastras);
        writer.Close();
    }

    public void DeserializeObject(string filename)
    {

        // Create the XmlSerializer using the XmlAttributeOverrides.
        XmlSerializer s =
           new XmlSerializer(typeof(Orchestras));

        FileStream fs = new FileStream(filename, FileMode.Open);
        Orchestras band = (Orchestras)s.Deserialize(fs);
        Console.WriteLine(band.orchestras[1].i);
        Console.WriteLine(band.orchestras[1].f);
        Console.WriteLine(band.orchestras[1].s1);
        Console.WriteLine(band.orchestras[1].s2);
        Console.WriteLine(band.orchestras[1].bc.dd);
        Console.WriteLine("Brass:");

        /* The difference between deserializing the overridden 
        XML document and serializing it is this: To read the derived 
        object values, you must declare an object of the derived type 
        (Brass), and cast the Instrument instance to it. */
        //Brass b;
        //Percussion p;
        Instrument b;
        // Percussion p;
        //b = (Brass)i;
        // int ii = 0;
        foreach (Instrument i in band.orchestras[1].Instruments)
        //foreach(Instrument i in band.List<Instrument>)
        {
            //        int i = 0;
            //   ii++;
            //  if (ii == 1)
            //   {
            b = i;
            Console.WriteLine(
                b.Name + "\n");

            // }
            /*if (ii == 2)
            {
                p = (Percussion)i;
                Console.WriteLine(
                    p.Name + "\n" +
                    p.name);

            }*/
        }
    }
}
使用系统;
使用System.IO;
使用System.Xml.Serialization;
使用System.Collections.Generic;
使用System.Xml;
公营乐团
{
公共列表乐团=新列表();
}
公共班管弦乐队
{
[XmlElement]
公共列表工具{get;set;}
公共国际一级;
公共基金;
公共字符串s1;
公共字符串s2;
公共B bc;
}
公共B级
{
公共双dd;
}
[xmlclude(类型(黄铜))]
[xmlclude(类型(打击))]
公共类文书
{
公共字符串名称;
}
公共课