I'm trying to refactor the following - which works, but if I start to get more elements in the XML it'll get unmanageable :
HttpResponseMessage response = await httpClient.GetAsync("https://uri/products.xml");
string responseAsString = await response.Content.ReadAsStringAsync();
List<Product> productList = new List<Product>();
XDocument xdocument = XDocument.Parse(responseAsString);
var products = xdocument.Descendants().Where(p => p.Name.LocalName == "item");
foreach(var product in products)
{
var thisProduct = new Product();
foreach (XElement el in product.Nodes())
{
if(el.Name.LocalName == "id")
{
thisProduct.SKU = el.Value.Replace("-master", "");
}
if (el.Name.LocalName == "availability")
{
thisProduct.Availability = el.Value == "in stock";
}
}
productList.Add(thisProduct);
}
Given the following XML URL
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://base.google.com/ns/1.0" version="0">
<channel>
<title>Product Feed</title>
<link></link>
<description>Products</description>
<item>
<availability>in stock</availability>
<id>01234-master</id>
...
</item>
<item>
<availability>in stock</availability>
<id>abcde-master</id>
...
</item>
</channel>
</rss>
Ideally I'd like to remove the loops and if statements and have a LINQ query that returns only the fields I need (id, availability etc..) from the XML in a nice clean way and populate a simple class with this data.
Can anyone help?