I am filling a list from an XML file. Some nodes may not exist and this causes an exception because it returns null. Here is the code:
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;
}
How can I make a controf before adding items to the list. Thank you.
exemple of the xml file :
<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>
code of 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>();
}
getXmlTransactions(pathXml)call. I showed several hints on parsing xml when nodes not exist in my answer, but you need to show that method definition (and xml you are trying to parse)