Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>4</PersonID>
  <UserName>a</UserName>
  <Thumbnail>a</Thumbnail>
</Person>
like image 701
tempid Avatar asked Apr 22 '13 15:04

tempid


People also ask

How do I get XML response from Web API?

Debug the Application and in the URL write the http://localhost:32266/api/detail. Then it shows the result on browser in XML form.

Can Rest return XML?

Data types that REST API can return are as follows: JSON (JavaScript Object Notation) XML. HTML.

How does Web API send XML data?

If you want to send XML data to the server, set the Request Header correctly to be read by the sever as XML. xmlhttp. setRequestHeader('Content-Type', 'text/xml'); Use the send() method to send the request, along with any XML data.


1 Answers

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 => (int)x.Element("PersonID") == personId);

    var xml = new XElement("TheRootNode", result).ToString();
    return new HttpResponseMessage 
    { 
        Content = new StringContent(xml, Encoding.UTF8, "application/xml") 
    };
}
like image 120
Darin Dimitrov Avatar answered Sep 28 '22 06:09

Darin Dimitrov