2017-04-15 31 views
2

我是在linq到xml的begginer。我有一个xml文件,我想读它,并且选择对象(自行车)通过Id。 我的测试XML文件是:通过id linq选择一个对象到xml C#

<Bikes> 
<!--- - - - - - - - - - - - - - - - - - - -A new Bike- - - - - - - - - - - - - - - - - - - --> 
    <Bike Id="1"> 
     <Big_Picture>Image</Big_Picture> 
     <Small_Picture>Image</Small_Picture> 
     <Emblem_Picture>Image</Emblem_Picture> 
     <Firm>Image</Firm> 
     <Model>Image</Model> 
     <Price>Image</Price> 
     <Colour>Image</Colour> 
     <Frame_Size>Image</Frame_Size> 
     <Description>Image</Description> 
     <Gears>Image</Gears> 
     <Groupset>Image</Groupset> 
     <Brakes>Image</Brakes> 
     <Frame_Material>Image</Frame_Material> 
     <Wheel>Image</Wheel> 
    </Bike> 
</Bikes> 

我想ID选择此自行车(1),然后把这种自行车的元素在我的类(自行车)的对象。我怎样才能做到这一点?我的代码,当然,不执行任务:

XDocument xdoc = XDocument.Load("Bikes.xml"); 
xdoc.Descendants("Bike").Select(p => new { 
     id = p.Attribute("Id").Value, 
     picture = p.Element("Small_Picture").Value, 
     model = p.Element("Model").Value, 
     price = p.Element("Price").Value 
    }).ToList().ForEach(p => { 
     Bike bike = new Bike(p.id, p.picture, p.model, p.price);//Constructor 
     bikes_xml.Add(bike); 
    }); 
+1

“不起作用”是什么意思? –

+0

对不起,错误地表示 – Eldar

+0

这是什么问题?什么不起作用? – CodingYoshi

回答

0

如果你想获取一个自行车,你的问题,然后使用FirstOrDefault

var data = XDocument.Load("data.xml") 
        .Descendants("Bike") 
        .FirstOrDefault(item => item.Attribute("Id").Value == "1"); 
if(data != null) 
{ 
    Bike bike = new Bike(data.Attribute("Id").Value, 
         data.Element("Small_Picture").Value, 
         data.Element("Model").Value, 
         data.Element("Price").Value); 
} 

如果你想建造其在LINQ语法则:

Bike x = (from bike in XDocument.Load("data").Descendants("Bike") 
      select new Bike(bike.Attribute("Id").Value, 
          bike.Element("Small_Picture").Value, 
          bike.Element("Model").Value, 
          bike.Element("Price").Value)) 
     .FirstOrDefault(item => item.Id == 1);  

和@SelmanGenç建议,看看你是否可以更改使用Object Initializer而不是带有参数的构造函数。更多关于它的检查What's the difference between an object initializer and a constructor?

+0

谢谢,第一个变体是我需要的。 – Eldar

+0

@Eldar - 欢迎您:)考虑对象初始值设定项与构造函数提示:) –

1

如果不起作用你的意思是你所得到的所有项目,所有你需要的是一个Where

var bikes = xdoc.Descendants("Bike") 
       .Where(e => (int)e.Attribute("Id") == 1) 
       .Select(p => new 
       { 
        id = p.Attribute("Id").Value, 
        picture = p.Element("Small_Picture").Value, 
        model = p.Element("Model").Value, 
        price = p.Element("Price").Value 
       }).ToList(); 

如果您尚未使用属性,则可以将其更改为使用属性,因此您无需创建匿名类型。你可以只用new Bike { ... }