2013-01-10 109 views
0

我使用WCF做我的网络服务项目。问题是,我有一个XML文件,该文件是这样的:XML解析通过LINQ

<Cars> 
    <Make Name="Honda"> 
     <Model Name="Accord" Year="2013"> 
      <Price>22480</Price> 
     </Model> 
     <Model Name="Civic" Year="2013"> 
      <Price>17965</Price> 
     </Model> 
     <Model Name="Crosstour" Year="2013"> 
      <Price>27230</Price> 
     </Model> 
     <Model Name="CR-V" Year="2013"> 
      <Price>22795</Price> 
     </Model> 
    </Make> 
</Cars> 

我要检索的Price对于给定的Model其中Name属性由用户提供。我正在使用这种方法:

var DBCodes = from Cars in XmlEdit.Descendants("Cars") 
    from Make in Cars.Elements("Make") 
    from Made in Make.Elements("Made") 
    where Made.Attribute("Name").Value == CarName //Variable for Name 
    select Make; 

foreach (var Make in DBCodes) 
{ 
    if (Make != null) 
     PriceOfCar = Make.Element("Price").Value.ToString(); 
    else 
     break; 
} 

但它不工作。我在哪里犯错?

+1

是不是'从模型Make.Elements( “模型”)'? – vlad

+0

哪里是'Made'元素?你只有'Model'的名字,或者你也应该寻找'Make'的名字吗?你的xml中有几个'Make'元素吗?如果你有多个'Civic'型号不同年? –

+1

@vlad大声笑。我已经工作了这么久,我的脑海里哽咽。 :D非常感谢。我忘了我自己的模式!事情只是通过模型来解决。 – TriumphTruth

回答

3
var cars = 
    XDocument.Load("a.xml") 
     .Descendants("Make") 
     .Select(make => new 
     { 
      Name = make.Attribute("Name").Value, 
      Models = make.Descendants("Model") 
         .Select(model => new{ 
          Name = (string)model.Attribute("Name"), 
          Year = (int)model.Attribute("Year"), 
          Price = (int)model.Element("Price") 
         }) 
         .ToList() 
     }) 
     .ToList(); 



string userInput="Civic"; 
var price = cars.SelectMany(c => c.Models).First(m => m.Name == userInput).Price; 

你甚至可以直接从XML得到的价格而不将其转换成一个临时搭建

string userInput="Civic"; 
var price = (int)XDocument.Load("a.xml") 
      .Descendants("Model") 
      .First(m => (string)m.Attribute("Name") == userInput) 
      .Element("Price"); 
+0

非常感谢大家的帮助。该方法是正确的。只有拼写错误。 – TriumphTruth