<T> list as an XML response from a WCF service?

I have a WCF operation that returns a list of colors:

public List<Color> GetColors() { List<Color> colors = new List<Color>(); colors.Add(new Color {Name = "Red", Code = 1}); colors.Add(new Color {Name = "Blue", Code = 2}); return colors; } 

When I run this in the WCF test client, it works fine and I can see an array of colors, but I would like it to return an XML response, and then I could set the RichTextBox text to the xml content. How can i do this?

+4
source share
3 answers

If you want the XML representation of the list to be returned to the client, my advice would be to serialize the list and return it as a string to the client.

Here is the code you can get started. Not tested, but I think it will be easy for you to change.

 public string GetColorsXmlRepresentation() { var colors = new List<Color>(); colors.Add(new Color {Name = "Red", Code = 1}); colors.Add(new Color {Name = "Blue", Code = 2}); return Serialize<List<Color>>(colors); } public string Serialize<T>(T instance) { var data = new StringBuilder(); var serializer = new DataContractSerializer(instance.GetType()); using (var writer = XmlWriter.Create(data)) { serializer.WriteObject(writer, instance); writer.Flush(); return data.ToString(); } } 

Hope this helps

+2
source

If you want the WCF service to return XML, return XML. If you want it to return a List<Color> , it should return a List<Color> .

+1
source

You cannot use open generics in WCF contracts. SOAP does not have generic support.

0
source

All Articles