monsey11 monsey11 - 11 months ago 67
C# Question

C# XML find first Element descendants

Looking to find

for first
It could also return no products.

XML Looks like this

<findItemsByKeywordsResponse xmlns="http://...">
<searchResult count="1">
<categoryName>**Catg Nameee**</categoryName>

Full xml here

Answer Source

Because your root element has a namespace defined what you should do when searching for the descendant items is specify the namespace:

XNamespace ns = @"";
var result = XDocument.Load("data.xml")
          .Descendants(ns + "item")
          .FirstOrDefault()?.Element(ns + "primaryCategory");

var categoryId = result?.Element(ns + "categoryId")?.Value;
var categoryName = result?.Element(ns + "categoryName")?.Value;

Also you can use C# 6.0 Null Propagation (?:) to retrieve the <primaryCategory> in a more elegant way. Keep in mind that if you do not have an <item> tag or a <primaryCategory> tag the result will be equal to null

In addition it might make more sense to try and find the first <item> that answers some predicate. If that is the case change the .FirstOrDefault() with: .FirstOrDefault(item => item.Element("itemId").Value == "12345") for example