使用LINQ从XML中取回数据

问题描述:

<Vehicle> 
    <CheckPoints ID="11"> 
    <Days Day="1">check</Days> 
    </CheckPoints> 
    <CheckPoints ID="10"> 
    <Days Day="1">check</Days> 
    </CheckPoints> 
</Vehicle> 

我想用LINQ查询记录。 我的问题是,我想迭代到每个节点并将CheckPoints ID与我的ID匹配,然后想要获得当天的Days文本。 (根据正在进行的月份,每个CheckPoints将具有Max 31 Days节点)。 请帮忙。使用LINQ从XML中取回数据

+3

LINQ到XML:http://msdn.microsoft.com/en-us/library/bb387098.aspx – Martin 2010-11-01 12:16:12

+1

接受其他的问题! – Svisstack 2010-11-01 12:18:32

+0

你可以告诉我这个发现的副作用带ID的CheckPoints,并写一个新的节点的文字在其中? – Nipun 2010-11-04 08:56:07

试试这个

var xmlstr = @"<Vehicle> <CheckPoints ID=""11""> <Days Day=""1"">check</Days> </CheckPoints> <CheckPoints ID=""11""> <Days Day=""2"">check</Days> </CheckPoints><CheckPoints ID=""10""> <Days Day=""1"">check</Days> </CheckPoints></Vehicle>"; 
var id=11; 
var currDay = DateTime.Now.Day; 
var xl = XElement.Load(new StringReader(xmlstr)); 
var resxml = from el in xl.Descendants("CheckPoints") 
      where Convert.ToInt32(el.Attribute("ID").Value) == id 
      select el into x 
      from ell in x.Descendants("Days") 
      where Convert.ToInt32(ell.Attribute("Day").Value) <= currDay 
      select ell; 

foreach (var xres in resxml) 
{ 
    Console.Write(xres.Value); 
} 
+0

感谢这个例子。但是我需要直到日期data.Like如果今天是第五,那么我需要直到日期从XML数据5,因为将有5个节点在每个CheckPoints – Nipun 2010-11-01 13:08:23

+0

@Nipun,“ell.Attribute(”日“)。价值) RameshVel 2010-11-01 14:05:14

+0

你可以告诉我这个发现的副作用带有ID的CheckPoints和写一个新的节点的文本在其中吗?我的意思是说,我想写在具有指定值的resxml中 – Nipun 2010-11-04 10:43:46