如何从使用DataContractSerializer序列化的对象的XML表示中删除XML命名空间?
该对象需要序列化为非常简单的输出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();
}
}
从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);
}
}
答案 0 :(得分:46)
您需要标记要序列化的类:
[DataContract(Namespace="")]
在这种情况下,数据协定序列化程序不会对序列化对象使用任何命名空间。
马克
答案 1 :(得分:11)
如果您的心脏设置绕过默认行为(就像我目前所做的那样),您可以创建一个绕过编写命名空间的自定义XmlWriter。
using System.IO;
using System.Xml;
public class MyXmlTextWriter : XmlTextWriter
{
public MyXmlTextWriter(Stream stream)
: base(stream, null)
{
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
base.WriteStartElement(null, localName, "");
}
}
然后在你的作家消费者中,如下所示:
var xmlDoc = new XmlDocument();
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
using (var ms = new MemoryStream())
{
using (var writer = new MyXmlTextWriter(ms))
{
serializer.WriteObject(writer, obj);
writer.Flush();
ms.Seek(0L, SeekOrigin.Begin);
xmlDoc.Load(ms);
}
}
输出中会有命名空间声明,但不会有这样的用法:
<TestObject xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Items xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>Item1</string>
<string>Item2</string>
</Items>
</TestObject>