1

I want to serialize a list to xml (from a web-api method).

public class Result
{
  public List<string> Users { get; set; }
}

So I get for example:

<result>
  <user>Paul</user>
  <user>David</user>
  <user>Joan</user>
</result>

So far, I get:

<result>
  <users>
    <user>Paul</user>
    <user>David</user>
    <user>Joan</user>
  </users>
</result>

How do I tell the serialization not to wrap the user list in a "users" tag?

Thanks.

2
  • 1
    Can you just return List<User> from web api? Commented Jun 17, 2015 at 14:57
  • Thanks, yes, except in reality there is more in the Result object than just a list of User objects. Commented Jun 17, 2015 at 15:39

2 Answers 2

1

You could either derive from XmlObjectSerializer and implement your own XML Serializer (see here FMI) or else manipulate your type so it works with the default formatter. Which isn't a great solution, but may work for a simple example, like so:

public class Result : List<User>
{
    //Any user added to Result will be nested directly within Result in the XML
}

Further reading:

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the thoughts and links. In reality, there is more data in the Result class than just a list of User objects though, which seems to make it a little more complicated.
Yeah, I figured there would be. Hope the links help -- best of luck with your efforts!
1

You need to replace default DataContractSerializer with XmlSerializer in Application_Start method.

For whole project:

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

For specific type:

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.SetSerializer<Result>(new XmlSerializer(typeof(Result)));

After this you can use attributes to format your xml output:

public class Result
{
  [XmlElement("user")]
  public List<string> Users { get; set; }
}

2 Comments

I haven't tried it, so I'm just curious: wouldn't that just attempt to rename the <users> element to <user>, rather than eliminating that level of the hierarchy?
It is eliminating level of hierarchy - XmlElement replaces default behavior of XmlArray.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.