XML序列化不能正确导出列表

本文关键字:列表 序列化 不能 XML | 更新日期: 2023-09-27 18:19:01

我正在尝试将一个对象序列化为XML,它应该生成这样的XML文档:

<?xml version="1.0" encoding="UTF-8"?>
<XMLFile xmlns="http://www.google.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <channels>
  <Ch01>
    <Name>Test Channel 01</Name>
    <Number>1</Number>
  </Ch01>
  <Ch02>
    <Company>Google</Company>
    <Founded>2015-10-23T13:04:04.2048888+01:00</Founded>
    <Founder>Some Guy</Founder>
  </Ch02>
  </channels>
</XMLFile>

不幸的是,当我做序列化时,标签丢失了,我花了两个小时试图找出它,我有一个同事看了看,他们也被难住了,下面是代码的副本(不是我们项目的真正的东西)它有同样的问题。

测试代码:

        XMLFile file = new XMLFile();
        file.channels.Add(new Ch01() {Name = "Test Channel 01", Number = 1});
        file.channels.Add(new Ch02() {Company = "Google", Founded = DateTime.Now, Founder = "Some Guy"});
        XMLSerialize.SerializeToXml(Application.StartupPath + "//test.xml", file);

XMLFile:

[Serializable]
public class XMLFile
{
    public XMLFile()
    {
    }
    [XmlElement(Type = typeof(Ch01))]
    [XmlElement(Type = typeof(Ch02))]
    public List<channel> channels = new List<channel>(); 
}
通道:

[Serializable]
public class channel
{
    public channel()
    {
    }
}

Ch01:

[Serializable]
public class Ch01 : channel
{
    public Ch01()
    {
    }
    public string Name;
    public int Number;
}

Ch02:

[Serializable]
public class Ch02 : channel
{
    public Ch02()
    {
    }
    public string Company;
    public DateTime Founded;
    public string Founder;
}

XMLSerialize:

public static class XMLSerialize
{
    public static void SerializeToXml<T>(string file, T value)
    {
        var serializer = new XmlSerializer(typeof(T), "http://www.google.com");
        using (var writer = XmlWriter.Create(file))
            serializer.Serialize(writer, value);
    }
    public static T DeserializeFromXML<T>(string file)
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(T), "http://www.google.com");
        TextReader textReader = new StreamReader(file);
        T result;
        result = (T)deserializer.Deserialize(textReader);
        textReader.Close();
        return result;
    }

下面是我得到的输出:

<?xml version="1.0" encoding="UTF-8"?>
<XMLFile xmlns="http://www.google.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <Ch01>
      <Name>Test Channel 01</Name>
      <Number>1</Number>
   </Ch01>
   <Ch02>
      <Company>Google</Company>
      <Founded>2015-10-23T13:04:04.2048888+01:00</Founded>
      <Founder>Some Guy</Founder>
   </Ch02>
</XMLFile>

这个项目将生成一个巨大的XML文件,所以通过XmlDocument手动创建它不是一个好的选择。

任何想法?

XML序列化不能正确导出列表

正如评论中建议的那样,您可以使用XmlArray,但您需要指定派生类的类型,如下所示:

public class XMLFile
{
    public XMLFile()
    {
    }
    [XmlArray("channels")]
    [XmlArrayItem(Type = typeof(Ch01), ElementName = "Ch01")]
    [XmlArrayItem(Type = typeof(Ch02), ElementName = "Ch02")]
    public List<channel> channels = new List<channel>();
}