'Extract common class with different XML namespaces
I have two identical classes:
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; }
}
}
I would like to extract TheClass to Models.Common namespace to share it between Models.CSharpNamespace1 and Models.CSharpNamespace2, but there is a difference between them in namespace in XmlType attribute.
This namespace is essential for SOAP, so I can't change it.
What to do?
Solution 1:[1]
Here is how to do it
POCO class (XmlTypeAttribute is removed)
public partial class TheClass
{
[XmlAttribute]
public string Prop1 { get; set; }
[XmlAttribute]
public string Prop2 { get; set; }
[XmlAttribute]
public int Prop3 { get; set; }
}
Serialization
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());
}
Output:
<TheClass Prop1="Prop1" Prop2="Prop2" Prop3="3" xmlns="http://XmlNamespace2" />
Sample fiddle: https://dotnetfiddle.net/2ctFdk
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cinchoo |
