I'm creating an xml feed of products which needs to match the clients scheme exactly.
I'm using web api. I would like the property extractDate to be an attribute. The following code is outputting extractDate as an element not an attribute
public Feed GetProducts()
{
var feed = new Feed()
{
extractDate = "extractDate",
incremental = true,
name = "name",
Brands = GetBrands(),
Categories = GetCategories(),
Products = GetProducts()
};
return feed;
}
Here is my model Feed. Note the following doesn't seem to turn the element into an attribute
[XmlAttribute(AttributeName = "extractDate")]
public class Feed
{
[XmlAttribute(AttributeName = "extractDate")] //attribute is ignored
public string extractDate { get; set; }
public bool incremental { get; set; }
public string name { get; set; }
public List<Brand> Brands { get; set; }
public List<Category> Categories { get; set; }
public List<Product> Products { get; set; }
}
How do i output
<feed extractDate="2012/01/01"
// other logic
/>
The model binding system: Retrieves data from various sources such as route data, form fields, and query strings. Provides the data to controllers and Razor pages in method parameters and public properties. Converts string data to . NET types.
When Web API calls a method on a controller, it must set values for the parameters, a process called binding. By default, Web API uses the following rules to bind parameters: If the parameter is a "simple" type, Web API tries to get the value from the URI.
The REST API Client Service currently accepts only JSON input when making REST API Create, Read, Update, or Delete requests. It is nevertheless possible to use XML input when making REST API requests.
Web API by default uses DataContractSerializer in XmlMediaTypeFormatter and probably that's the reason you are not seeing your attribute decorations taking effect. Do you have the XmlSerializer enabled on the XmlMediaTypeFormatter to see your expected output?
config.Formatters.XmlFormatter.UseXmlSerializer = true;
Also, you could set XmlSerializer only for specific types too using the following api:
config.Formatters.XmlFormatter.SetSerializer<>
Edit
Managed to simulate your issue with a blank project and Kiran's answer seems to do the trick.
Just add this line in your controller(for testing purposes, it should probably be in your global.asax)
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
Do you have the [XmlRoot] on top of your class or is it missing?
Not sure the attribute will work without an xml class decorator.
A simple sanity check you could do is serialize the class without web api involved to make sure it's nothing silly but actually web api related.
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