.net - 防止 XmlSerializer 发出 xsi :type on inherited types

标签 .net xml xml-serialization

我设法将从基类继承的类序列化为 XML。但是,.NET XmlSerializer 生成如下所示的 XML 元素:

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

然而,这会导致 Web 服务的接收端阻塞并产生一个错误,该错误相当于:抱歉,我们不知道“DerivedType”。

如何防止 XmlSerializer 发出 xsi:Type 属性?谢谢!

最佳答案

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

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

//produces

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

如果你真的想完全删除 type 属性,你可以编写自己的 XmlTextWriter,它会在写入时跳过该属性(灵感来自 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)

关于.net - 防止 XmlSerializer 发出 xsi :type on inherited types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1729711/

相关文章:

javascript - 可以工作,但是非常慢...使用 JS 调用 XML,然后将 JS 函数添加到 XML 中的文本

xml - 在 Oracle 存储过程中将 XmlType 转换为 CLOB

java - 使用 xstream 自定义 java 集合的序列化

.net - 在 WPF FlowDocument 中实现脚注

.net - GetAsyncKeyState 是否有 .Net 替代品?

c# - 从字符串中匹配英语词典单词

php - 将 XML 加载到 SQL 时组契约(Contract)名的 XML 字段

c# - 使用 XML 序列化序列化接口(interface)列表

c# - 空的序列化 XML 文件

mysql - MySQL Connector Net 6.8.3 的问题