我在C#中使用LINQ to XML。我有下面的代碼,最後一行不斷拋出一個System.Exception:值不能爲空。我無法弄清楚問題所在。我已經嘗試了一切。 AuthorizedToSign是一個列表。我能夠使用大型嵌套的foreach循環執行相同的操作。 我知道肯定沒有錯誤,只要XML文件本身。 如果有人能幫助,我將不勝感激。LINQ to XML「System.Exception:值不能爲空」
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>
,並且您試圖讀取看起來像XML文件...? –
請顯示完整的堆棧跟蹤。 –
我要猜測並說'a.Element(「Status」)。Value'是'null','Enum.Parse'則拋出這個異常。 –