Hi Couple of points -
Is there a way to return something better formatted, like JSON or XML?
And How do I do that?
From WEB API perspective if the object is serializable then it will automatically convert to well formatted XML or JSON. So instead of returning a string return the "books" which is an IEnumerable in this case so you don't have to worry about formatting.
You may have to also see these below discussions on the same --
WebAPI to Return XML
You are trying to fetch specific books based on title
Would also want to suggest instead of checking against Value instead of XmlElement, So replace the below line
x => x.Element("title").ToString().ToLower().Contains(id)
with -
x => x.Element("title").Value.ToString().ToLower().Contains(id)
So the final code which you would be writing is for list of specific books -
public IEnumerable<XElement> Get(string id)
{
XElement xelement = XElement.Load("C:/Users/potter/source/repos/library/lib/Controllers/books.xml");
return xelement.Elements("book").Where(x => x.Element("title").Value.ToString().ToLower().Contains(id));
}
Once you have this set up in server side then you can call the API from client side using jQuery ajax something like below -
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://localhost:50116/api/values/GetData/",//Change this to your URL
cache: false,
data: {id:'xml'},//Title has this word 'xml'
dataType: "xml",
success: function (xml) {
$(xml).find('book').each(function () {
var name = $(this).find("title").text();
var genre = $(this).find("genre").text();
var price = $(this).find("price").text();
var description = $(this).find("description").text();
alert(name);
alert(genre);
alert(price);
alert(description);
});
}
});
});