I'm having some problems with my WebAPI. I have followed the guide from Microsoft and it works: https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api?fbclid=IwAR0tEMDMX3URn2YO0pwnTTAbY2RuGkdu-HUobznac4Lwus6rOVPSeiX-lFs
Now I want to be able to get data from my XML file instead of the hardcoded values the guide use. I have tried to search for this already but not sure I find the right thing. How can I do this?
Code I have tried:
public IEnumerable<Book> GetAllProducts()
{
XDocument doc = XDocument.Load("C:\\Users\\Name\\Desktop\\products.xml");
foreach (XElement element in doc.Descendants("Catalog")
.Descendants("Product"))
{
Product product = new Product();
product.Id = element.Element("Id").Value;
product.Name = element.Element("Name").Value;
product.Category = element.Element("Category").Value;
product.Added_Date = element.Element("Added_Date").Value;//this will not work because its not a string
product.Price = element.Element("Price").Value;//this will not work because its not a string
products.Add(product);
}
return products;
}
XML Code:
<?xml version="1.0"?>
<catalog>
<product id="P1">
<name>Royal Gala</name>
<category>Apple</category>
<country>New Zeeland</country>
<price>33.00</price>
<added_date>2011-01-11</added_date>
<description>This is a lovely red apple.</description>
</product>
<product id="P2">
<name>Granny Smith</name>
<category>Apple</category>
<country>Australia</country>
<price>33.00</price>
<added_date>2013-12-25</added_date>
<description>This is a lovely green apple.</description>
</product>
</catalog>