Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add xsi:type attribute to an XML element

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.

like image 866
Dhinesh Avatar asked Jan 11 '23 08:01

Dhinesh


1 Answers

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>
like image 121
Reinder Wit Avatar answered Jan 18 '23 22:01

Reinder Wit