How can I add xsi:type in xml element.
I am writing a routine in C# which is serializing an Xml file using XmlSerializer. Everything seems to be fine except something I first thought was a minor but turned out not to be so.
here is my code,
public class OuterElement
        {
            public string firstElement { get; set; }
            public string secondElement { get; set; }
            public InnerElement innerElement = new InnerElement();
        }
        public class InnerElement
        {            
            [XmlAttribute(AttributeName="xsi:type")]
            public string type { get; set; }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(OuterElement));
            OuterElement outerElement = new OuterElement();
            outerElement.firstElement = "name";
            outerElement.secondElement = "CD";
            outerElement.innerElement.type = "testsample";
            using (TextWriter writer = new StreamWriter(@"G:\abc.xml"))
            {
                serializer.Serialize(writer, outerElement);
            }
        }
'
I want xml like this,
<OuterElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" lns:xsd="http://www.w3.org/2001/XMLSchema">
    <innerElement xsi:type="testsample">     
    </innerElement>
    <firstElement>name</firstElement> 
    <secondElement>CD</secondElement> 
</OuterElement>
Thanks in advance.
You need to declare the correct namespace for the attribute, like so:
public class InnerElement
{
    [XmlAttribute(Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string type = "bla";
}
This will produce your desired output:
<OuterElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <innerElement xsi:type="testsample" />
    <firstElement>name</firstElement>
    <secondElement>CD</secondElement>
</OuterElement>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With