【问题标题】:find the highest value in multiple xml files and display them在多个 xml 文件中找到最大值并显示它们
【发布时间】:2016-04-14 12:48:49
【问题描述】:

我有这个 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);
    }

请问有什么解决办法吗?

【问题讨论】:

  • 您的示例 xml 文件充满了语法错误。 标签没有结束标签, 标签以 标签结束。请先修复它。
  • @Seprum 我解决了这个问题。对不起,我复制了错误的文件!程序也可以毫无问题地读取 xml 文件,但我只需要从每个 xml 文件中打印最高价格(我有 10 个,所以我必须有 10 个价格)
  • 如果适合您,我可以将 XML 发布到 LINQ 解决方案。
  • 如果这行得通并且能做我想做的事,那就太好了! @Seprum

标签: c# xml


【解决方案1】:

这里是您的案例的 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 文件使用此方法即可获得所需的最高值。

【讨论】:

  • 我使用了它,但它显示一个错误,它没有找到 xml 文件(其中一个)我忘了提到我正在使用线程等一次读取所有 xml 文件。跨度>
  • 不是这个代码问题。如果您希望得到进一步的帮助,请提供有关您如何加载文件的更多信息。
  • 我正在使用 OpenFileDialog 加载我的文件。我有一个类,它采用 xml 文件的名称并将其作为字符串返回到需要的位置
  • 我加了!请检查一下
【解决方案2】:

看起来您的局部变量一直被覆盖,并且只有最后的最高价格。

str = locationList.carHighestPrice (highest.locationName).Last() + Environment.NewLine;

你可以尝试用

替换上面的行吗
str = string.Concat(str, locationList.carHighestPrice (highest.locationName).Last(),Environment.NewLine)

【讨论】:

  • 但是错误不存在,它在@Seprum 给我的方法上
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多