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:
<
Use XElement
like this:
from rt in results.descendants("<node name>")
where rt.attribute(attribute name).value == "specified value"
select rt
Sorry for typing from cell phone
With LINQ you can easily select just the nodes that have a specified attribute, like this:
var query = from node in results.Descendants("arr") // I believe you could use results.Elements("arr") here
where node.Attribute("name").Value == "ATR_FamilyName"
select new Product
{
FamilyName = node.Element("str").Value
};
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
.)