Return HttpResponseMessage with XML data

[Originally Posted By]: http://stackoverflow.com/questions/16151191/return-httpresponsemessage-with-xml-data

I’ve created a WebAPI using .NET. The API reads/writes data from an xml file. I have the following code and it returns the matching elements without a root element. How do I make it return with root?

API Controller:

[HttpGet]
public HttpResponseMessage GetPerson(int personId)
{
   var doc = XDocument.Load(path);
   var result = doc.Element("Persons")
          .Elements("Person")
          .Single(x => (int)x.Element("PersonID") == personId);
   return new HttpResponseMessage() { Content = new StringContent(string.Concat(result), Encoding.UTF8, "application/xml") };
}

Result:

<Person>
  <PersonID>1</PersonID>
  <UserName>b</UserName>
  <Thumbnail />
</Person><Person>
  <PersonID>2</PersonID>
  <UserName>b</UserName>
  <Thumbnail />
<Person><Person>
  <PersonID></PersonID>
  <UserName></UserName>
  <Thumbnail></Thumbnail>
</Person>
shareedit

You could wrap the result in a root element:

[HttpGet]
public HttpResponseMessage GetPerson(int personId)
{
    var doc = XDocument.Load(path);
    var result = doc
        .Element("Persons")
        .Elements("Person")
        .Single(x =&gt; (int)x.Element("PersonID") == personId);

    var xml = new XElement("TheRootNode", result).ToString();
    return new HttpResponseMessage 
    { 
        Content = new StringContent(xml, Encoding.UTF8, "application/xml") 
    };
}
shareedit
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s