I have an xml file that returns a set of elements that are unique by a attribute value. This presents a problem, as I can not select a node by its name:
<
Like AS-CII's answer, but without using a query expression (except for the outer one), and with the cast for XAttribute, and selecting the str element value inside an anonymous type:
select new Product.Product
{
FamilyName = rt.Descendants("arr")
.Where(x => (string) x.Attribute("name") == "ATR_FamilyName")
.Select(x => (string) x.Element("str"))
.FirstOrDefault(),
MorePropertiesToSet....
};
Note that the use of a cast for the result of the call to Attribute("name") means that if there are any elements which don't have the attribute, the cast will result in a null reference (which isn't equal to the string literal). If you use the Value property, you'll get an exception. Sometimes an exception may be better - if that indicates that the data is fundamentally broken and you want to find out about it rather than just not match the value.
(The same is true for the cast of the XElement to string.)