C# 数组 XML 序列化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/126155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 14:45:41  来源:igfitidea点击:

C# Array XML Serialization

提问by Fionn

I found a problem with the XML Serialization of C#. The output of the serializer is inconsistent between normal Win32 and WinCE (but surprisingly WinCE has the IMO correcter output). Win32 simply ignores the Class2 XmlRoot("c2")Attribute.

我发现 C# 的 XML 序列化有问题。序列化程序的输出在普通 Win32 和 WinCE 之间不一致(但令人惊讶的是 WinCE 具有 IMO 校正器输出)。Win32 只是忽略 Class2XmlRoot("c2")属性。

Does anyone know a way how to get the WinCE like output on Win32 (because i don't want the XML tags to have the class name of the serialization class).

有谁知道如何在 Win32 上获得类似 WinCE 的输出(因为我不希望 XML 标签具有序列化类的类名)。

Test Code:

测试代码:

using System;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleTest
{
    [Serializable]
    [XmlRoot("c1")]
    public class Class1
    {
        [XmlArray("items")]
        public Class2[] Items;
    }

    [Serializable]
    [XmlRoot("c2")]
    public class Class2
    {
        [XmlAttribute("name")]
        public string Name;
    }

    class SerTest
    {
        public void Execute()
        {
            XmlSerializer ser = new XmlSerializer(typeof (Class1));

            Class1 test = new Class1 {Items = new [] {new Class2 {Name = "Some Name"}, new Class2 {Name = "Another Name"}}};

            using (TextWriter writer = new StreamWriter("test.xml"))
            {
                ser.Serialize(writer, test);
            }
        }
    }
}

Expected XML (WinCE generates this):

预期的 XML(WinCE 生成此):

<?xml version="1.0" encoding="utf-8"?>
<c1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <items>
    <c2 name="Some Name" />
    <c2 name="Another Name" />
  </items>
</c1>

Win32 XML (seems to be the wrong version):

Win32 XML(似乎是错误的版本):

<?xml version="1.0" encoding="utf-8"?>
<c1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <items>
    <Class2 name="Some Name" />
    <Class2 name="Another Name" />
  </items>
</c1>

采纳答案by Ray Lu

Try [XmlArrayItem("c2")]

尝试 [XmlArrayItem("c2")]

[XmlRoot("c1")]
public class Class1
{
    [XmlArray("items")]
    [XmlArrayItem("c2")] 
    public Class2[] Items;
}

or [XmlType("c2")]

或 [XmlType("c2")]

[XmlType("c2")]
public class Class2
{
    [XmlAttribute("name")]
    public string Name;
}