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 pre
From code you provided I can say, that you are passing null
to getXmlComptes
method (or to getXmlTransactions
if it is called elsewhere).
I suggest you to cast elements:
public static List<Transaction> getXmlTransactions(XElement n)
{
if (n == null)
throw new ArgumentNullException("Konto is null");
var transactions = from t in n.Elements("Transaktion")
select new Transaction {
TransID = (string)t.Element("TransID"),
TypeTransaction = (string)t.Element("TransArt"),
DateEntree = (string)t.Element("BuchDat"),
Montant = (string)t.Element("BetragWAE"),
Devise = (string)t.Element("BuchDat"),
Pays = (string)t.Element("GegenLandText"),
AbreviationPays = (string)t.Element("GegenLand"),
autresinfo = (string)t.Element("Kommentar")
};
return transactions.ToList();
}
And second method:
public static List<Compte> getXmlComptes(XElement n)
{
if (n == null)
throw new ArgumentNullException("Something is null");
var comptes = from k in n.Elements("Konto")
select new Compte
{
NumCompte = (string)k.Element("KtoNr"),
typeCompte = (string)k.Element("KontoArt"),
DateOuverture = (string)k.Element("KtoOeff"),
IBAN = (string)k.Element("IBAN"),
Devise = (string)k.Element("Waehrung"),
CommentairesCompte = (string)k.Element("Kommentar"),
Trans = getXmlTransactions(k)
};
return comptes.ToList();
}
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:
TypeTransaction = (string)t.Element("TransArt") ?? ""
But I would keep property value as null
to show that it was not in xml.