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

问题描述 投票:0回答:1

这是我的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不能在属性名中序列化冒号(:)......我如何解决这个问题?如果我从属性名中删除冒号,它就能正常工作。

c# xml xml-serialization
1个回答
0
投票

做它的正确方式。

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; }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.