C# XML 序列化如何设置属性 xsi:type [英] C# XML Serialization How To Set Attribute xsi:type

查看:128
本文介绍了C# XML 序列化如何设置属性 xsi:type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 Xml 处理 XML 序列化后的样子:

This is how my Xml should look after XML Serialization:

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

这就是我的 C# 代码:

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

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

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 ..

推荐答案

以正确的方式去做:

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

这篇关于C# XML 序列化如何设置属性 xsi:type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆