How to define xml attributes using web api and model binding

I am creating a product XML file that should exactly match the client schema.

I am using web api. I would like the extractDate property to be an attribute. The following code displays 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 Feed model. Note that the following does not 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 to withdraw

 <feed extractDate="2012/01/01" // other logic /> 
+6
source share
3 answers

The web API by default uses the DataContractSerializer in the XmlMediaTypeFormatter and probably the reason you don't see your attribute attributes take effect. Do you have the XmlSerializer included in the XmlMediaTypeFormatter to see your expected result?

config.Formatters.XmlFormatter.UseXmlSerializer = true;

In addition, you can also install XmlSerializer only for certain types using the following api:

config.Formatters.XmlFormatter.SetSerializer<>

+10
source

Edit
Managed to mimic your problem with an empty project, and Kiran's answer seems to do the trick.
Just add this line to your controller (for testing purposes, this should probably be in your global.asax)

 GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true; 

Do you have [XmlRoot] on top of your class or is it missing?
Not sure if the attribute will work without an xml class decorator.
A simple sanity check that you can do is to serialize the class without the participation of a web api to make sure that it is not stupid, but is actually related to web api.

+3
source

How about this:

 [XmlRoot("feed")] public class Feed { [XmlAttribute(AttributeName = "extractDate")] 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; } } 
0
source

Source: https://habr.com/ru/post/946402/


All Articles