Web Api XML, How to set Encoding, Version, xmlns:xsi and xsi:schemaLocation

asp.net-mvc-4, asp.net-web-api, xml-encoding, xmlserializer

Solution

This answer is one year delayed and tested for WebAPI2!

Enable XML declaration in your `WebApiConfig` class

config.Formatters.XmlFormatter.WriterSettings.OmitXmlDeclaration = false;

Then add `schemaLocation` property or member (I always prefer property)

public class SampleData
{
    [XmlAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string SchemaLocation { get; set; }

    //other properties
    public string Prop1 { get; set; }

    public SampleData()
    {
        SchemaLocation = "http://localhost/my.xsd";
    }
}

Output:

<?xml version="1.0" encoding="utf-8"?>
<TestModel 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="http://localhost/my.xsd">
    <Prop1>1</Prop1>
</TestModel>

Problem

I am using asp.net MVC4 Web Api. I have set: ``` Dim xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter xml.UseXmlSerializer = True ``` I have created a class that specifies the XML I need and this works well. I am almost there but I am not sure how set the: ``` <?xml version="1.0" encoding="utf-8"?> ``` and how to set the element attributes: xmlns:xsi and xsi:schemaLocation Can I set this using an attribute?

Original source