I am retireving data from xml field, there are nodes that may not exist (because the xml file is generated dynamically) . the problem is when I look for a node and it is not present in the file , it returns a null list and this exception :"d Object reference not set to an instance of an object ". Here is the code :
public static List<Transaction> getXmlTransactions(XElement n)
{
var transactions = n.Elements("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,
DateEntree = p.Element("BuchDat") != null ? p.Element("BuchDat").Value : String.Empty,
Montant = p.Element("BetragWAE") != null ? p.Element("BetragWAE").Value : String.Empty,
Devise = p.Element("BuchDat") != null ? p.Element("Waehrung").Value : String.Empty,
// BanqueCorespondante = p.Element("BuchDat") != null ? p.Element("Waehrung").Value : String.Empty, Dans le compte
Pays = p.Element("GegenLandText") != null ? p.Element("GegenLandText").Value : String.Empty,
AbreviationPays = p.Element("GegenLand") != null ? p.Element("GegenLand").Value : String.Empty,
autresinfo = p.Element("Kommentar") != null ? p.Element("Kommentar").Value : String.Empty
}).ToList();
return transactions;
}
public static List<Compte> getXmlComptes(XElement n)
{
var comptes = n.Elements("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,
DateOuverture = p.Element("KtoOeff") != null ? p.Element("KtoOeff").Value : String.Empty,
IBAN = p.Element("IBAN") != null ? p.Element("IBAN").Value : String.Empty,
Devise = p.Element("Waehrung") != null ? p.Element("Waehrung").Value : String.Empty,
CommentairesCompte = p.Element("Kommentar") != null ? p.Element("Kommentar").Value : String.Empty,
Trans = getXmlTransactions(p)
}).ToList();
return comptes;
}
From code you provided I can say, that you are passing
null
togetXmlComptes
method (or togetXmlTransactions
if it is called elsewhere).I suggest you to cast elements:
And second method:
Run this code and you'll see were you are passing
null
. If you need to assign empty string to some property if element is missing in xml, then use null-coalescing operator:But I would keep property value as
null
to show that it was not in xml.