Linq to XML selecting a node bases on a attribute value

前端 未结 3 1169
情书的邮戳
情书的邮戳 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:29

    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

    0 讨论(0)
  • 2021-01-04 12:33

    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
                };
    
    0 讨论(0)
  • 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.)

    0 讨论(0)
提交回复
热议问题