gpt4 book ai didi

.net - 使用 DataContractSerializer 序列化没有命名空间的对象

转载 作者:太空宇宙 更新时间:2023-11-03 16:27:22 27 4
gpt4 key购买 nike

如何从使用 DataContractSerializer 序列化的对象的 XML 表示中删除 XML 命名空间?

该对象需要序列化为非常简单的输出 XML。

  • 最新最好的 - 使用 .Net 4 beta 2
  • 永远不需要反序列化对象。
  • XML 不应有任何 xmlns:... 命名空间引用
  • 需要支持 Exception 和 ISubObject 的任何子类型。
  • 改变原始对象将非常困难。

对象:

 [Serializable] 
class MyObj
{
string str;
Exception ex;
ISubObject subobj;
}

需要序列化为:

<xml>
<str>...</str>
<ex i:nil="true" />
<subobj i:type="Abc">
<AbcProp1>...</AbcProp1>
<AbcProp2>...</AbcProp2>
</subobj>
</xml>

我使用了这段代码:

private static string ObjectToXmlString(object obj)
{
if (obj == null) throw new ArgumentNullException("obj");

var serializer =
new DataContractSerializer(
obj.GetType(), null, Int32.MaxValue, false, false, null,
new AllowAllContractResolver());

var sb = new StringBuilder();
using (var xw = XmlWriter.Create(sb, new XmlWriterSettings
{
OmitXmlDeclaration = true,
NamespaceHandling = NamespaceHandling.OmitDuplicates,
Indent = true
}))
{
serializer.WriteObject(xw, obj);
xw.Flush();

return sb.ToString();
}
}

来自 this article我采用了 DataContractResolver,因此无需声明任何子类型:

public class AllowAllContractResolver : DataContractResolver
{
public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
{
if (!knownTypeResolver.TryResolveType(dataContractType, declaredType, null, out typeName, out typeNamespace))
{
var dictionary = new XmlDictionary();
typeName = dictionary.Add(dataContractType.FullName);
typeNamespace = dictionary.Add(dataContractType.Assembly.FullName);
}
return true;
}

public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
{
return knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null) ?? Type.GetType(typeName + ", " + typeNamespace);
}
}

最佳答案

您需要标记要序列化的类:

[DataContract(Namespace="")]

在这种情况下,数据协定序列化程序不会为您的序列化对象使用任何命名空间。

马克

关于.net - 使用 DataContractSerializer 序列化没有命名空间的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12144497/

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