Linq to XML selecting a node bases on a attribute value

前端 未结 3 1201
情书的邮戳
情书的邮戳 2021-01-04 12:16

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:

<         


        
3条回答
  •  醉话见心
    2021-01-04 12:45

    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.)

提交回复
热议问题