Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 202
Marcel Avatar asked Oct 28 '12 12:10

Marcel


1 Answers

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>
like image 163
LostInComputer Avatar answered Oct 09 '22 19:10

LostInComputer