从发光XSI prevent XmlSerializer的:类型上继承类型 [英] Prevent XmlSerializer from emitting xsi:type on inherited types

查看:123
本文介绍了从发光XSI prevent XmlSerializer的:类型上继承类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法序列化的类继承自一个基类的XML。但是,.NET XmlSerializer的产生,看起来XML元素如下:

I have managed to serialize a class that inherits from a base class to XML. However, the .NET XmlSerializer produces an XML element that looks as follows:

<BaseType xsi:Type="DerivedType" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

然而,这会导致网络服务的接收端呛,并产生相当于一个错误:对不起,我们不知道DerivedType

This, however, causes the receiving end of a web service to choke and produce an error that amounts to: sorry we do not know "DerivedType".

我怎么能prevent XmlSerializer的从发光的xsi:type属性?谢谢!

How can I prevent the XmlSerializer from emitting the xsi:Type attribute? Thanks!

推荐答案

您可以使用的 XmlType将属性以指定类型属性另一个值:

You can use the XmlType attribute to specify another value for the type attribute:

[XmlType("foo")]
public class DerivedType {...}

//produces

<BaseType xsi:type="foo" ...>

如果你真的想彻底删除该类型的属性,你可以写你自己的XmlTextWriter,这将跳过属性书面形式(通过的此博客条目​​):

If you really want to entirely remove the type attribute, you can write your own XmlTextWriter, which will skip the attribute when writing (inspired by this blog entry):

public class NoTypeAttributeXmlWriter : XmlTextWriter
{
    public NoTypeAttributeXmlWriter(TextWriter w) 
               : base(w) {}
    public NoTypeAttributeXmlWriter(Stream w, Encoding encoding) 
               : base(w, encoding) { }
    public NoTypeAttributeXmlWriter(string filename, Encoding encoding) 
               : base(filename, encoding) { }

    bool skip;

    public override void WriteStartAttribute(string prefix, 
                                             string localName, 
                                             string ns)
    {
        if (ns == "http://www.w3.org/2001/XMLSchema-instance" &&
            localName == "type")
        {
            skip = true;
        }
        else
        {
            base.WriteStartAttribute(prefix, localName, ns);
        }
    }

    public override void  WriteString(string text)
    {
        if (!skip) base.WriteString(text);
    }

    public override void WriteEndAttribute()
    {
        if (!skip) base.WriteEndAttribute();
        skip = false;
    }
}
...
XmlSerializer xs = new XmlSerializer(typeof(BaseType), 
                                     new Type[] { typeof(DerivedType) });

xs.Serialize(new NoTypeAttributeXmlWriter(Console.Out), 
             new DerivedType());

// prints <BaseType ...> (with no xsi:type)

这篇关于从发光XSI prevent XmlSerializer的:类型上继承类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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