Making some reasonable guesses about what your Employee
class looks like, you need to do the following:
Decorate your Employee
class with [XmlRoot("MT_Get_Name_Req", Namespace = "http://hsd.sd.com")]
. This will give your XML root element the correct name and namespace.
While the root is in the http://hsd.sd.com
namespace, its child elements are not in any namespace. Thus their namespace will need to be overridden using an XmlElement
attribute.
Setting the XmlRoot
namespace will use the specified namespace as the default namespace. If you must use a prefixed namespace, you need to pass a XmlSerializerNamespaces
with all desired namespaces to XmlSerializer.Serialize()
.
Thus:
[XmlRoot("MT_Get_Name_Req", Namespace = Employee.XmlNamespace)]
public class Employee
{
public const string XmlNamespace = "http://hsd.sd.com";
public const string XmlNamespacePrefix = "ns0";
const string xsi = "http://www.w3.org/2001/XMLSchema-instance";
const string xsd = "http://www.w3.org/2001/XMLSchema";
public static XmlSerializerNamespaces XmlSerializerNamespaces
{
get
{
var namespaces = new XmlSerializerNamespaces();
namespaces.Add(XmlNamespacePrefix, XmlNamespace);
// namespaces.Add("xsi", xsi); Uncomment to add standard namespaces.
// namespaces.Add("xsd", xsd);
return namespaces;
}
}
[XmlElement("personnel_id", Namespace="")]
public string personnel_id { get; set; }
[XmlElement("dob", Namespace = "")]
public string dob { get; set; }
}
And use it like
var xml = XmlSerializationHelper.GetXml(employee, Employee.XmlSerializerNamespaces, Encoding.UTF8);
Using the extension methods:
public static class XmlSerializationHelper
{
public sealed class StringWriterWithEncoding : StringWriter
{
private readonly Encoding encoding;
public StringWriterWithEncoding(Encoding encoding)
{
this.encoding = encoding;
}
public override Encoding Encoding
{
get { return encoding; }
}
}
public static string GetXml<T>(T obj, XmlSerializerNamespaces ns, Encoding encoding)
{
return GetXml(obj, new XmlSerializer(obj.GetType()), ns, encoding);
}
public static string GetXml<T>(T obj, XmlSerializer serializer, XmlSerializerNamespaces ns, Encoding encoding)
{
using (var textWriter = new StringWriterWithEncoding(encoding))
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true; // For cosmetic purposes.
settings.IndentChars = " "; // For cosmetic purposes.
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
{
if (ns != null)
serializer.Serialize(xmlWriter, obj, ns);
else
serializer.Serialize(xmlWriter, obj);
}
return textWriter.ToString();
}
}
}
To get
<?xml version="1.0" encoding="utf-8"?>
<ns0:MT_Get_Name_Req xmlns:ns0="http://hsd.sd.com">
<personnel_id>1202</personnel_id>
<dob>19470906</dob>
</ns0:MT_Get_Name_Req>