The easiest approach is to perform a simple get against your object to get an example of the XML to send back.
Things to remember:
- Include the namespace
xmlns:i="http://www.w3.org/2001/XMLSchema-instance" this is needed to indicate null values
- If using the standard XML serialiser config you need the namespace too e.g.
xmlns="http://schemas.datacontract.org/2004/07/MvcApplication10.Controllers"
- When doing a get set the accept header to
accept: application/xml
- When posting to the controller set content type.
content-type: application/xml
Using the example object and controller.
public class Foo
{
public string Bar { get; set; }
}
public class FoosController : ApiController
{
// GET api/foos
public Foo Get()
{
return new Foo { Bar = "Test" };
}
// GET api/foos
public Foo Post(Foo test)
{
return test;
}
}
I do a GET on the /api/foos and get an example object:
User-Agent: Fiddler
Host: localhost
accept: application/xml
Response:
<Foo xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MvcApplication10.Controllers"><Bar>Testing</Bar></Foo>
To Post it back I simply set the content-type header alter a value in the xml and post it back:
User-Agent: Fiddler
Host: localhost:61280
content-type: application/xml
Content-Length: 167
Request
<Foo xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MvcApplication10.Controllers"><Bar>Testing Response</Bar></Foo
Response
<Foo xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MvcApplication10.Controllers"><Bar>Testing Response</Bar></Foo>
Update
For complicated XML models you need to start using DataContract annotations http://msdn.microsoft.com/en-us/library/ms731045.aspx.
Example:
[DataContract(Name = "Person")]
public class Foo
{
[DataMember(Name = "Address", IsRequired = False)]
public string Bar { get; set; }
}
This alters the XML required
<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MvcApplication10.Controllers"><Address>Testing Response</Address></Person>
For collections etc look here http://msdn.microsoft.com/en-us/library/aa347850.aspx