C# Linq到XML基于属性值选择节点

C# Linq到XML基于属性值选择节点,c#,linq,linq-to-xml,C#,Linq,Linq To Xml,我有一个xml文件,它返回一组元素,这些元素通过属性值是唯一的。这带来了一个问题,因为我无法按节点名称选择节点: <doc> <float name="score">1.2873721</float> <arr name="2_category"> <long>3021</long> </arr> <arr name="ATR_FamilyName">

我有一个xml文件,它返回一组元素,这些元素通过属性值是唯一的。这带来了一个问题,因为我无法按节点名称选择节点:

<doc>
    <float name="score">1.2873721</float>
    <arr name="2_category">
        <long>3021</long>
    </arr>
    <arr name="ATR_FamilyName">
        <str>Some Cookbook </str>
    </arr>
    <arr name="ATR_IsFamily">
        <str>0</str>
    </arr>
    <arr name="ATR_SellPrice">
        <str>49.95</str>
    </arr>
    <arr name="ATR_VendorId">
        <str>ABC</str>
    </arr>
    <arr name="ATR_VendorName">
        <str>WROX</str>
    </arr>      
</doc> 
以下是我的linq到xml查询:

var query = from rt in results
   where (String)rt.Descendants().ElementAt(5).Element("str").Value == "0"
   select new Product.Product
             {
                FamilyName = (String)rt.Descendants().ElementAt(3).Value
                // doc/arr[@name = 'ATR_FamilyName']/str - select Family Name is arr/@name 'ATR_FamilyName'                              
                MorePropertiestoset....                              
              };   

使用LINQ,您可以轻松地仅选择具有指定属性的节点,如下所示:

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
            };
from rt in results.descendants("<node name>")
where rt.attribute(attribute name).value == "specified value"
select rt

与AS-CII的答案类似,但不使用查询表达式(外部表达式除外),使用
XAttribute
的强制转换,并在匿名类型中选择
str
元素值:

select new Product.Product
{
    FamilyName = rt.Descendants("arr")
                   .Where(x => (string) x.Attribute("name") == "ATR_FamilyName")
                   .Select(x => (string) x.Element("str"))
                   .FirstOrDefault(),
    MorePropertiesToSet....                              
}; 
请注意,对调用
属性(“name”)
的结果使用强制转换意味着,如果有任何元素没有该属性,则强制转换将导致空引用(不等于字符串文本)。如果使用
属性,则会出现异常。有时,异常可能更好—如果这表明数据从根本上被破坏,并且您希望了解它,而不是仅仅与值不匹配


(将
XElement
转换为
string
时也是如此)

像这样使用
XElement

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
            };
from rt in results.descendants("<node name>")
where rt.attribute(attribute name).value == "specified value"
select rt
来自results.substands中的rt(“”)
其中rt.attribute(属性名).value==“指定值”
选择rt

乔恩,很抱歉用手机输入了关于演员阵容的解释。我遇到的情况不是所有节点都有该属性,它会抛出一个异常,因为我使用了.Value而不是cast;这就是菲德克斯。