C# XML Serialization How To Set Attribute xsi:type

一世执手 提交于 2021-02-11 15:39:28

问题


This is how my Xml should look after XML Serialization:

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

Thats my C# code to it:

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

Apparently the XmlSerializer can't serialize colons (:) in attributenames.... how do i fix this problem? If i remove the colon from the attributeName itm works out fine ..


回答1:


Do it the correct way :

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; }
    }
}


来源:https://stackoverflow.com/questions/61407681/c-sharp-xml-serialization-how-to-set-attribute-xsitype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!