0

我正在使用 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>

我想检索用户提供属性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;
}

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

4

1 回答 1

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");
于 2013-01-10T21:17:53.430 回答