我有这个xml文件:(它是一个草案,并有多个像这样)
<?xml version="1.0" encoding="UTF-8" ?>
<Car>
<Location name = "somewhere">
<Type type="itstype">
<Color>Blue</Color>
<Owner>Bill</Owner>
<Price>135</Price>
</Type>
</Location>
<Location name = "somewhere">
<Type type="itstype">
<Color>Red</Color>
<Owner>John</Owner>
<Price>250</Price>
</Type>
</Location>
</Car>
我希望使用C#来读取所有xml文件(我可以这样做)并找到每个xml文件中每辆车的最高价格并在屏幕上显示它们。 (例如,我有10个xml文件,我必须从每个xml文件中打印出10个高价格,以及具有该价格的汽车名称)有些xml文件有两个以上的汽车。 我尝试使用它,但它只显示它读取的最后一个xml文件的最高价格。
public List<Cars> carHighestPrice (string carsname)
{
var highest = from hv in locations
from HV in hv.cars
orderby HV.votes
where hv.locationName == carsName
select HV;
return highest.ToList();
}
这是我用来显示它们的方法
public void DisplayHighestPrices()
{
string str = "";
foreach (var highest in locationList.locations)
{
str = locationList.carHighestPrice (highest.locationName).Last() + Environment.NewLine;
}
lbl1.Text = str;
}
编辑:
public String XMLFileName { get; private set; }
public configXML(String XMLFileName)
{
this.XMLFileName = XMLFileName;
}
public override String ToString()
{
return String.Format("{0}", XMLFileName);
}
有关如何解决这个问题的任何想法吗?
答案 0 :(得分:0)
以下是针对您的案例的LINQ to XML解决方案:
public int HighestPrice(string xmlFilePath)
{
var doc = XDocument.Load(xmlFilePath);
var cars = doc.Root.Elements("Location").Select(e => e.Element("Type"));
return cars.Max(c => int.Parse(c.Element("Price").Value));
}
只需对每个xml文件使用此方法即可获得所需的最高值。
答案 1 :(得分:0)
看起来您的本地变量一直被覆盖,并且只有最高价格。
str = locationList.carHighestPrice (highest.locationName).Last() + Environment.NewLine;
您可以尝试用
替换上面的行吗?str = string.Concat(str, locationList.carHighestPrice (highest.locationName).Last(),Environment.NewLine)