通过LINQ进行XML解析

本文关键字:解析 XML 进行 LINQ 通过 | 更新日期: 2023-09-27 17:51:13

我正在使用WCF做我的web服务项目。问题是,我有一个这样的XML文件:

<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>

我想检索给定ModelPrice,其中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;
}

但是它不起作用。我哪里出错了?

通过LINQ进行XML解析

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");