gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 01:39:32 26 4
gpt4 key购买 nike

我设法将从基类继承的类序列化为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com