[英]Exception C# null list
我正在從XML文件填充列表。 某些節點可能不存在,這會導致異常,因為它返回null。 這是代碼:
public static List<Compte> getXmlComptes(string pathXml)
{
var doc = XDocument.Load(pathXml);
var comptes = doc.Descendants("Anzeige").Descendants("Kunde").Descendants("Konto").Select(p => new Compte()
{
NumCompte = p.Element("KtoNr") != null ? p.Element("KtoNr").Value : String.Empty,
typeCompte = p.Element("KontoArt") != null ? p.Element("KontoArt").Value : String.Empty,
Trans = getXmlTransactions(pathXml)
}).ToList();
return comptes;
}
在將項目添加到列表之前,如何進行控制。 謝謝。
xml文件的示例:
<Anzeige>
<Kunde>
<IdClient>ppp</IdClient>
<Konto>
<NumCompte>258</NumCompte>
<Transaction>
<idTrans>85555</idTrans>
<type>blebleble</type>
</Transaction>
<Transaction>
<idTrans>85555</idTrans>
<type>blebleble</type>
</Transaction>
</Konto>
</Kunde>
</Anzeige>
getXmlTransaction的代碼:
public static List<Transaction> getXmlTransactions(string pathXml)
{
var doc = XDocument.Load(pathXml);
var transactions = doc.Descendants("Anzeige").Descendants("Kunde").Descendants("Konto").Descendants("Transaktion").Select(p => new Transaction()
{
TransID = p.Element("TransID") != null ? p.Element("TransID").Value : String.Empty,
TypeTransaction = p.Element("TransArt") != null ? p.Element("TransArt").Value : String.Empty
}).ToList();
if (transactions != null)
return transactions.ToList();
else
return new List<Transaction>();
}
使用將元素強制轉換為字符串,而不是直接讀取其值。 如果未找到element,則將使用null
字符串而不是異常:
var doc = XDocument.Load(pathXml);
var comptes = doc.Descendants("Anzeige")
.Descendants("Kunde")
.Descendants("Konto")
.Select(k => new Compte {
NumCompte = (string)k.Element("KtoNr"),
typeCompte = (string)k.Element("KontoArt"),
Trans = getXmlTransactions(k)
}).ToList();
如果要在找不到元素時使用空字符串而不是null
,則可以使用null-coalescing運算符
NumCompte = (string)p.Element("KtoNr") ?? ""
使用相同的技術來解析可能不存在的節點。 而且我很確定這是getXmlTransactions(pathXml)
方法引發異常。
更新:獲取事務時不要加載整個xml文檔。 您將如何知道要讀取哪些Konto元素事務。 改為傳遞Konto元素並獲取其交易:
public static List<Transaction> getXmlTransactions(XElement konto)
{
return konto.Elements("Transaction")
.Select(t => new Transaction {
TransID = (string)t.Element("idTrans"),
TypeTransaction = (string)t.Element("type")
}).ToList();
}
注意:您在<Transaction>
(代替Transaktion
)中具有<idTrans>
(代替TransID
)和<type>
(代替TransArt
)元素! xml中也沒有KtoNr
和KontoArt
元素。 仔細閱讀元素名稱。 另外,與其尋找所有后代,不如在直系子代中搜索:
doc.Root.Elements("Kunde").Elements("Konto") ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.