C# XML 序列化如何设置属性 xsi:type

C# XML Serialization How To Set Attribute xsi:type

这就是我的 Xml 应该如何处理 XML 序列化:

<value xsi:type="CD" otherAttributes= "IDK">
.
.
.
</value>

这就是我的 C# 代码:

public class Valué
{
    [XmlAttribute(AttributeName ="xsi:type")]
    public string Type { get; set; } = "CD";
    [XmlAttribute(attributeName: "otherAttributes")]
    public string OtherAttributes { get; set; } = "IDK"
}

显然 XmlSerializer 无法序列化属性名称中的冒号 (:)...我该如何解决这个问题? 如果我从 attributeName 中删除冒号,结果很好..

正确的做法:

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            Valué value = new CD() { OtherAttributes = "IDK" };
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(FILENAME, settings);
            XmlSerializer serializer = new XmlSerializer(typeof(Valué));
            serializer.Serialize(writer, value);

        }
    }
    [XmlInclude(typeof(CD))]
    public class Valué
    {
    }
    public class CD : Valué
    {
        [XmlAttribute(attributeName: "otherAttributes")]
        public string OtherAttributes { get; set; }
    }
}