Rassal KP Rassal KP - 5 days ago 9
C# Question

Generate XML using namespace prefix in c#

what is the modification i need to provide for the code to bring out below xml

<?xml version="1.0"?>
<CheckInLoad xmlns="http://fake.com/schemas/insert" xmlns:cmn="http://fake.com/schemas/common" >
<Input>
<cmn:EmpId>100</cmn:EmpId>
</Input>
</CheckInLoad>


Here is the class dfinition

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://fake.com/schemas/Insert")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://fake.com/schemas/Insert", IsNullable = false)]
public partial class CheckInLoad
{
private CheckInLoadHeader headerField;
public CheckInLoadHeader Header
{
get
{
return this.headerField;
}
set
{
this.headerField = value;
}
}
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://fake.com/schemas/Insert")]
public partial class CheckInLoadHeader
{

private string empIdField;


/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://fake.com/schemas/common")]
public string EmpId
{
get
{
return this.empIdField;
}
set
{
this.empIdField = value;
}
}

}


Please let me know what kind of change needs to be done at class level. please not that, i am using below code to convert object to xml

var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(load.GetType());
serializer.Serialize(stringwriter, load);
return stringwriter.ToString();

Answer
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("cmn", "http://fake.com/schemas/common");
XmlSerializer serializer = new XmlSerializer(load.GetType());
serializer.Serialize(stringwriter, load, ns);

Try this.

Comments