简体   繁体   中英

Why foreach loop fail with one child element in XML?

I get a object reference not set to an instance of an object when parsing through the foreach loop below. It works if there is more than one child element of RecordTypeCode. When one child element of RecordTypeCode it throws the exception. The XML file can have RecrdTypeCode of WORKSITE and HOME. This file only had WORKSITE. Using Newtonsoft Json Linq.

JObject person from XML. The error occurs on the second line of code (the if statement)

foreach (JToken item in person.SelectToken("MessageContent.Employee.Addresses.AddressDetail"))
{
    if (item.SelectToken("RecordTypeCode").ToString() == "WORKSITE")
    {
        address = item.SelectToken("AddressLine1").ToString();
        address = address + " " + item.SelectToken("AddressLine2").ToString();
        //address = address + " " + item.SelectToken("City").ToString();
        state = item.SelectToken("StateProvinceCode").ToString();
        zip = item.SelectToken("PostalCode").ToString();
    }
}

If I get the string from person.SelectToken("MessageContent.Employee.Addresses.AddressDetail") for the failing employee I get :

"ReferenceObjectCode": "Employees", "AddressType": "EmployeeAddressDetail", "RecordTypeCode": "WORKSITE", "AddressLine1": "700 Main St Ste 1100", "AddressLine2": null, "AddressLine3": null, "City": "Kansas City", "StateProvinceCode": "MO", "PostalCode": "64112", "County": "Jackson", "CountryCode": "US", "UniqueID": "ABD4AAB5-7BF0-4814-21AF-FF639BBB50E2"

This is a bit of an educated guess based on some Netwonsoft documentation I found ( https://www.newtonsoft.com/json/help/html/SelectToken.htm ), as well as a very useful correcting comment by Brian Rodgers.

Basically, SelectToken will return a single JToken, not an enumerable you can loop through (I'm not sure how the code you posted works for multiple finds, to be honest; the posted code seems like it should always fail.)

What you want is SelectTokens, which returns a collection you can loop through. (See https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JToken_SelectTokens.htm )

Though, again, you should follow RogerN's comment (so that a missing element won't cause a crash in the future) and break it down to follow SRP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM