如何从使用 DataContractSerializer 序列化的对象的 XML 表示中删除 XML 命名空间?
How do I remove XML namespaces from an object's XML representation serialized using DataContractSerializer?
该对象需要序列化为一个非常简单的输出 XML.
That object needs to be serialized to a very simple output XML.
对象:
[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();
}
}
来自 这篇文章我采用了一个DataContractResolver,因此不必声明子类型:
From this article I adopted a DataContractResolver so that no subtypes have to be declared:
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);
}
}
你需要标记你想要序列化的类:
You need to mark the classes you want to serialize with:
[DataContract(Namespace="")]
在这种情况下,数据协定序列化程序不会为您的序列化对象使用任何命名空间.
In that case, the data contract serializer will not use any namespace for your serialized objects.
马克
这篇关于使用 DataContractSerializer 序列化没有命名空间的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!