tempid
tempid

Reputation: 8208

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>

Upvotes: 7

Views: 18468

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

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") 
    };
}

Upvotes: 16

Related Questions