Reputation: 4366
I'm attempting to setup a Web API endpoint that has a specific requirement that the XML format be similar to this:
<broadcast> <name></name> <description></description> <episode> <title></title> </episode> <episode> <title></title> </episode> ... </broadcast>
My models look like this:
[DataContract] public class broadcast { [DataMember] public string name { get; set; } [DataMember] public string description { get; set; } [DataMember] public List<episode> episodes { get; set; } } [DataContract] public class episode { [DataMember] public string title { get; set; } }
The problem I'm running into is that the episode
items get put into a container tag <episodes>. Is there any way to serialize the episodes
list so that the container tag doesn't appear?
Upvotes: 1
Views: 1867
Reputation: 181
You can use MessageContract instead DataContract. Message contracts describe the structure of SOAP messages sent to and from a service and enable you to inspect and control most of the details in the SOAP header and body:
[MessageContract]
public class broadcast
{
[MessageBodyMember]
public string name { get; set; }
[MessageBodyMember]
public string description { get; set; }
[MessageBodyMember]
public List<episode> episodes { get; set; }
}
Here you can find more information and details --> https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/using-message-contracts
Upvotes: 0
Reputation: 22406
Kyle's answer is almost correct. You need [XmlElement("episode")]
for this to work.
Upvotes: 1
Reputation: 4366
As it turns out there is a way to do this, but you must use the XmlSerializer
. To do this add the following line to to your WebApiConfig.cs
config.Formatters.XmlFormatter.UseXmlSerializer = true;
Then add the [XmlElement]
attribute to any collections you don't have to have a root tag. If you want to have a root tag use [XmlArray]
. So in my example above:
[XmlType] public class broadcast { [XmlElement] public string name { get; set; } [XmlElement] public string description { get; set; } [XmlElement] // could use [XmlArray] if I want a root tag public List episodes { get; set; } } [XmlType] public class episode { [XmlElement] public string title { get; set; } }
Upvotes: 2
Reputation: 20014
As far as I know removing the root element in a collection type is not possible. This is subject of Collection Type Serialization and even though there are multiple options to alter how collections are serialized using attributes like CollectionDataContractAttribute
there isn't an option to remove the root for the Serialized collection element.
Upvotes: 0