【问题标题】:Parsing Xml file with namespace and sorting values in descending order使用命名空间解析 Xml 文件并按降序对值进行排序
【发布时间】:2011-07-16 10:19:32
【问题描述】:

我正在尝试解析以下 xml 文件:http://reports.ieso.ca/public/DispUnconsHOEP/PUB_DispUnconsHOEP_20110714.xml

我的目标是获得最大的price 及其关联的hour 和最小的price 及其关联的hour

我应用的逻辑如下:

解析 Xml 文件并将其传递给包含 hourprice 对的 IList

根据price 以降序对IList 进行排序

检索 IList 中的第一个值作为最大值,而检索 IList 中的最后一个值作为最小值。

我的代码是:

XNamespace nsPriceHr = "http://www.theIMO.com/schema";
        XDocument xDocument =
            XDocument.Load("http://reports.ieso.ca/public/DispUnconsHOEP/PUB_DispUnconsHOEP_20110714.xml");
        XElement xEl1 = xDocument.Element(nsPriceHr + "IMODocument");
        XElement xEl2 = xEl1.Element(nsPriceHr + "IMODocBody");
        XElement xEl3 = xEl2.Element(nsPriceHr + "HOEPs");

        var data = (from x in xEl3.Descendants(nsPriceHr + "HOEP")
                    orderby x.Element(nsPriceHr + "Price").Value descending 
                    select new HourPrice
                    {
                        Hour = x.Element(nsPriceHr + "Hour").Value,
                        Price = x.Element(nsPriceHr + "Price").Value
                    })
                    .ToList();

我的问题是:列表没有按预期排序。采用HourPrice 这两个值的 HourPrice 对象的两个数据成员都是字符串。

我正在使用 C#、.NET 3.5 SP1 并使用 winforms。任何帮助表示赞赏

【问题讨论】:

    标签: c# .net winforms sorting ilist


    【解决方案1】:

    尝试使用System.Convert。特别是,您可能对ToInt32ToDecimal 感兴趣。这些函数接受一个字符串(或其他各种数据类型之一),并将其分别转换为 intdecimal

    var data = (from x in xEl3.Descendants(nsPriceHr + "HOEP")
        orderby System.Convert.ToDecimal(x.Element(nsPriceHr + "Price").Value) descending 
        select new HourPrice
        {
            Hour = System.Convert.ToInt32(x.Element(nsPriceHr + "Hour").Value),
            Price = System.Convert.ToDecimal(x.Element(nsPriceHr + "Price").Value)
        })
        .ToList();
    

    编辑:

    这是检查缺失值的一种方法:

    string valueString = x.Element("ElementName").Value;
    int value = String.IsNullOrEmpty(valueString) ? 0 : Convert.ToInt32(valueString);
    

    如果您的问题是字符串不为空,但格式也不正确,则必须在转换之前将它们转换为正确的格式。即,您必须从$6.47 之类的字符串中去除$

    【讨论】:

    • 我用过,但它给了我一个空异常错误并且不允许我转换
    • @reggie:你能发布异常消息的全文吗?什么给了你空引用?
    • @reggie:这意味着您尝试转换的字符串不是整数/十进制的有效表示。 HourPrice 中存储了哪些类型的字符串?它们必须是数字格式。 12pm 不起作用,$6.45 也不起作用。相反,它们必须是 126.45。此外,如果值为null(或空的string,您将遇到问题。在这种情况下,您可能希望默认为0 或抛出异常,具体取决于您是否可以接受缺失值。
    • 检查我在问题中提供的 xml 链接。这些值都不是空的,它们显然是数字。我不明白为什么它在排序或转换时出现问题。
    • @reggie:啊,很高兴你能修复它 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 2011-04-07
    • 2016-03-10
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    相关资源
    最近更新 更多