我正在使用 C# 中的 LINQ to XML。我有以下代码,最后一行不断抛出 System.Exception: Value cannot be null。我无法弄清楚问题是什么。我什么都试过了。AuthorizedToSign 是一个列表。我能够使用庞大的嵌套 foreach 循环执行相同的操作。我确信就 XML 文件本身而言没有错误。如果有人可以提供帮助,我将不胜感激。
BusinessAccounts = (from a in accountRoot.Elements()
where (bool)a.Element("Business") == true
select new BusinessAccount()
{
OpenDate = (DateTime)a.Element("DateOpened"),
Password = a.Element("Password").Value,
Balance = (double)a.Element("Balance"),
AccountStatus = (Status)Enum.Parse(typeof(Status), a.Element("Status").Value),
//Element AuthToSign has a collection of sub-elements called "authName"
//couldn't get the code below to work
AuthorizedToSign = (from el in a.Element("AuthorizedToSign").Elements()
                    select el.Element("AuthName").Value).ToList()
                                }).ToList();
更改select el.Element("AuthName").Value)
为      select (string)el.Element("AuthName"))
无济于事。
XML 文件有很多如下所示的条目:
<?xml version="1.0" encoding="utf-8"?>
<Accounts>
  <BusinessAccount>
    <Business>true</Business>
    <AccountNumber>34534456</AccountNumber>
    <AccountBranchID>100</AccountBranchID>
    <AccountName>Elgris Tech</AccountName>
    <CompanyName>Elgris Tech</CompanyName>
    <CompanyID>235</CompanyID>
    <CreditLimit>50000</CreditLimit>
    <DateOpened>2014-12-13T00:00:00</DateOpened>
    <Balance>1200</Balance>
    <Password>1234</Password>
    <Status>Active</Status>
    <AuthorizedToSign>
      <AuthName>Yechiel</AuthName>
      <AuthName>Lev</AuthName>
      <AuthName>Roman</AuthName>
    </AuthorizedToSign>
  </BusinessAccount>
  <PrivateAccount>
    <Business>false</Business>
    <AccountNumber>34534458</AccountNumber>
    <AccountBranchID>100</AccountBranchID>
    <AccountName>Yechiel L.</AccountName>
    <CustomerName>Yechiel L.</CustomerName>
    <CustomerAddress>2sadfasosa, CA</CustomerAddress>
    <CustomerPhone>8-4268</CustomerPhone>
    <CardNumber>304456</CardNumber>
    <CreditLimit>10000</CreditLimit>
    <DateOpened>1994-06-23T00:00:00</DateOpened>
    <Balance>555000</Balance>
    <Password>pass</Password>
    <Status>Active</Status>
  </PrivateAccount>
</Accounts>