我有两个类,我需要根据PackageItemNameSpace属性进入PackageItem属性的名称空间
因为我有几个从PackageItem继承的类,每个类都有自己的命名空间
public class Package
{
//HERE namespace dynamically, getting in YourName property
public PackageItem PackageItem {get;set;}
}
public class PackageItem
{
public string PackageItemNameSpace {get;set;}
}
如何设置命名空间的PackageItemNameSpace
属性?
我的序列化助手是:
public static string Serialize<T>(T obj, string @namespace = "", bool omitDeclaration = false, bool omitUnusedCharacters = true)
{
var serializer = new XmlSerializer(typeof(T), @namespace);
var xmlWriterSettings = new XmlWriterSettings()
{
Encoding = Encoding.UTF8
};
if (omitUnusedCharacters)
{
xmlWriterSettings.Indent = false;
xmlWriterSettings.NewLineChars = "";
xmlWriterSettings.NewLineOnAttributes = false;
}
if (omitDeclaration)
{
xmlWriterSettings.OmitXmlDeclaration = true;
xmlWriterSettings.ConformanceLevel = ConformanceLevel.Auto;
}
using (var stream = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
{
if (string.IsNullOrEmpty(@namespace))
{
serializer.Serialize(xmlWriter, obj);
}
else
{
var xmlSerializerNamespaces = new XmlSerializerNamespaces();
xmlSerializerNamespaces.Add("", @namespace);
serializer.Serialize(xmlWriter, obj, xmlSerializerNamespaces);
}
return stream.ToString();
}
}
}