0

我有以下代码

    var doc = XDocument.Load(@"export.xml");
    var companiesList = new Companies();

    var companies = (from c in doc.Descendants("Company")
                        select c).ToList();
    foreach (var xCompany in companies)
    {
        var company = new Company()
        {
            Name = (from x in xCompany.Descendants("Name") select x.Value).ToString(),
            Code = (from x in xCompany.Descendants("Code") select x.Value).ToString(),
            MaintenancePercentage =
                Convert.ToDouble(from x in xCompany.Descendants("MaintenancePercentage") select x.Value)
        };
        companiesList.AllCompanies.Add(company);
    }
    Console.WriteLine(companies);
    Console.ReadLine();
}

目前公司有 3000 家。我想将这些公司中的每一个都列在一个列表中。

public class Companies
{
    public Companies()
    {
        AllCompanies = new List<Company>();
    }

    public List<Company> AllCompanies;
}

public class Company
{
    public string Name;
    public string Code;
    public double MaintenancePercentage;
    public double AverageSales;
    public double TotalSales;
    public double TotalMaintenanceFee;
    public List<Sales> Saleses;
}

在 foreach 语句中,我收到错误消息 Error: Unable to cast object of type 'WhereSelectEnumerableIterator2[System.Xml.Linq.XElement,System.String]' to type 'System.IConvertible'。

知道我应该怎么做才能让它工作吗?

这是示例 xml 代码

<Companies>
    <Company>
    <Name>Name1</Name><Code>11014</Code>    
    <MaintenancePercentage>15.9</MaintenancePercentage>
     <Sales>
       <Sale>
       <Code>19538</Code>
       <Title>ABC</Title>
       <Date>2009-04-29T00:00:00</Date>
       <Category>Category1</Category>
       <Amount>6543.39</Amount>
       </Sale>
       <Sale>
       <Code>19539</Code>
       <Title>xyz</Title>
       <Date>2009-04-30T00:00:00</Date>
       <Category>Category2</Category>
       <Amount>654.39</Amount>
       </Sale>
    </Sales>
    </Company>

    <Company>
    <Name>Name1</Name><Code>11014</Code>     
<MaintenancePercentage>15.9</MaintenancePercentage>
     <Sales>
       <Sale>
       <Code>19538</Code>
       <Title>ABC</Title>
       <Date>2009-04-29T00:00:00</Date>
       <Category>Category1</Category>
       <Amount>6543.39</Amount>
       </Sale>
       <Sale>
       <Code>19539</Code>
       <Title>xyz</Title>
       <Date>2009-04-30T00:00:00</Date>
       <Category>Category2</Category>
       <Amount>654.39</Amount>
       </Sale>
    </Sales>
    </Company>
</Companies>
4

2 回答 2

0

LINQ 表达式

from x in xCompany.Descendants("Name") select x.Value

不返回单个对象,因此适用于 ToString 或 Convert.ToDouble 等结果函数并不完全正确,以获取单个值使用此扩展方法:

于 2013-10-22T10:31:39.540 回答
0

尝试这个:

Convert.ToDouble((from x in xCompany.Descendants("MaintenancePercentage") select x.Value).First())

为什么不使用反序列化?

要更正确地回答,有必要查看XML

于 2013-10-22T09:51:53.013 回答