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

1

6

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?

Elite answered 28/10, 2012 at 12:52 Comment(0)
B
6

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>
Banuelos answered 14/4, 2014 at 14:39 Comment(1)
This solution does not work on ASP.NET MVC 4.0 and WebApi on .NET 4.0. There is no WriterSettings in itTelethermometer

© 2022 - 2024 — McMap. All rights reserved.