我有两个相同的类:
namespace Models.CSharpNamespace1
{
[XmlType(Namespace = "http://XmlNamespace1")]
public partial class TheClass
{
[XmlAttribute]
public string Prop1 { get; set; }
[XmlAttribute]
public string Prop2 { get; set; }
[XmlAttribute]
public int Prop3 { get; set; }
}
}
namespace Models.CSharpNamespace2
{
[XmlType(Namespace = "http://XmlNamespace2")]
public partial class TheClass
{
[XmlAttribute]
public string Prop1 { get; set; }
[XmlAttribute]
public string Prop2 { get; set; }
[XmlAttribute]
public int Prop3 { get; set; }
}
}
我想提取TheClass
到Models.Common
的名称空间,以便在Models.CSharpNamespace1
和Models.CSharpNamespace2
之间共享,但它们在XmlType
属性中的名称空间上有所不同。这个名称空间对于SOAP是必不可少的,所以我不能更改它
该怎么办?
以下是的操作方法
POCO类(删除XmlTypeAttribute(
public partial class TheClass
{
[XmlAttribute]
public string Prop1 { get; set; }
[XmlAttribute]
public string Prop2 { get; set; }
[XmlAttribute]
public int Prop3 { get; set; }
}
序列化
public static void SerializeXml()
{
TheClass obj = new TheClass()
{
Prop1 = "Prop1",
Prop2 = "Prop2",
Prop3 = 3
};
//--> Pass the Namespace programmatically here
XmlSerializer s = new XmlSerializer(typeof(TheClass), "http://XmlNamespace2");
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = true
};
StringBuilder sb = new StringBuilder();
TextWriter w = new StringWriter(sb);
using (var writer = XmlWriter.Create(w, settings))
{
s.Serialize(writer, obj, namespaces);
}
Console.WriteLine(sb.ToString());
}
输出:
<TheClass Prop1="Prop1" Prop2="Prop2" Prop3="3" xmlns="http://XmlNamespace2" />
样品小提琴:https://dotnetfiddle.net/2ctFdk