C# 如何使用linq to xml获取属性的值?

C# 如何使用linq to xml获取属性的值?,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,但是,foreach语句从不激发。我做错了什么 编辑:对不起,我输入了错误的xml。正确的xml现在已经存在了首先,您应该使用.substands()而不是元素: var result = from el in doc.Elements("row") where (string)el.Attribute("typeName") == "Construction Blocks" select el.Attribute("typeID").Valu

但是,
foreach
语句从不激发。我做错了什么


编辑:对不起,我输入了错误的xml。正确的xml现在已经存在了

首先,您应该使用
.substands()
而不是
元素

var result = from el in doc.Elements("row")
             where (string)el.Attribute("typeName") == "Construction Blocks"
             select el.Attribute("typeID").Value;

foreach (string el in result)
{
    typeID.Add(Convert.ToInt32(el));
}
  • 要了解差异,请参阅:

在xml中,没有名为
构造块,因此结果将明显为空

所以foreach循环没有任何集合

var result = from el in doc.Elements("row")
             where (string)el.Attribute("typeName") == "Construction Blocks"
             select el.Attribute("typeID").Value;

foreach (string el in result)
{
    typeID.Add(Convert.ToInt32(el));
}
var result = (from el in doc.Descendants("row")
              where (string)el.Attribute("typeName") == "Construction Blocks"
              select Convert.ToInt32(el.Attribute("typeID").Value)).ToList();

// See that you can just perform the `Convert` in the `select` instead of having a 
// `foreach`. If you need to put the results into an initialized list then you can remove 
// the `ToList()` and just have an `AddRange` on your list to the `result`