我有以下代码
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 'WhereSelectEnumerableIterator
2[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>