0

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>();
}
5
  • Most likely you have exception in 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) Commented Jan 23, 2014 at 8:37
  • the content of getXmlTransaction(pathxml) is the same of getXmlComptes ,I called it because the Compte contains a list of transactions Commented Jan 23, 2014 at 8:43
  • I think it's not same. Also its not good re-loading whole xml to get child nodes of some element Commented Jan 23, 2014 at 8:45
  • I edited it, take a look and tell me, I think the problem is when there is no node <Konto> Commented Jan 23, 2014 at 8:59
  • I rolled back your edits. If you have another question, ask another questin Commented Jan 23, 2014 at 10:13

1 Answer 1

3

Use casting of element to string instead of reading it's value directly. If element was not found, you will have null string instead of exception:

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();

If you want empty string instead of null when element not found, you can use null-coalescing operator

NumCompte = (string)p.Element("KtoNr") ?? ""

Use same technique for parsing nodes which may not exist. And I'm pretty sure that it's getXmlTransactions(pathXml) method throws exception.

UPDATE: Do not load whole xml document when you are getting transactions. How would you know which Konto element transactions to read. Pass Konto element instead and get its transactions:

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();
}

NOTE: You have <idTrans> (instead TransID) and <type> (instead TransArt) elements in <Transaction> (instead Transaktion)! Also there is no KtoNr and KontoArt elements in your xml. Read element names carefully. Also instead of looking for all descendants it's better to search in direct children:

doc.Root.Elements("Kunde").Elements("Konto") ...
Sign up to request clarification or add additional context in comments.

15 Comments

Won't whis still throw when for example .Descendants("Kunde") isn't present?
@CodeCaster no, if Kunde not found, Descendants will return empty sequence
@CodeCaster I believe in getXmlTransactions(pathXml) - maybe he accesses some node value directly. I will ask him to update question with that method code
No the problem is when <Konto> is not present, it returns a null list, so it causes the exception
@user1503496 no, if Konto is not present Descendants("Knoto") will return empty sequence. Converting that sequence to list will give you empty list
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.