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>
Debug the Application and in the URL write the http://localhost:32266/api/detail. Then it shows the result on browser in XML form.
Data types that REST API can return are as follows: JSON (JavaScript Object Notation) XML. HTML.
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.
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")
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With