1

I'm having an issue with iterating through data when there is a self closing element.

In the first example it will end up skipping everything, in the second example I have no issues and it grabs the data I need.

<ENTRY>
         <NAME>Unbridled Halo</NAME>
         <DH_DQ_FLAGS/>
         <BREED>TB</BREED>
         <LAST_PP/>
         <WEIGHT>123</WEIGHT>
         <AGE>4</AGE>
</ENTRY>
// This has "LAST_PP" as a self closing


<ENTRY>
         <NAME>Our Prince</NAME>
         <DH_DQ_FLAGS/>
         <BREED>TB</BREED>
         <LAST_PP>
            <TRACK>
               <CODE>TAM</CODE>
               <NAME>TAMPA BAY DOWNS</NAME>
            </TRACK>
            <RACE_DATE>2020-04-19</RACE_DATE>
            <RACE_NUMBER>2</RACE_NUMBER>
            <OFL_FINISH>7</OFL_FINISH>
         </LAST_PP>
         <WEIGHT>123</WEIGHT>
         <AGE>4</AGE>

 </ENTRY>

Here is an example of the code I'm using.

        for names in xml["CHART"]["RACE"]["ENTRY"].all
//                capture and append data for each horse
          {
              var tempArray = [Any]()
              
             
                  
                 if let name = names["NAME"].element?.text,
                  let weight = names ["WEIGHT"].element?.text,
                  let age = names ["AGE"].element?.text,
                  let prevFIN = names ["LAST_PP"]["OFL_FINISH"].element?.text
                  
              {
                          
              tempArray.append(name)
              tempArray.append(Int(weight) ?? 0)
              tempArray.append(Int(age) ?? 0)            
              tempArray.append(Int(prevFIN) ?? 0)
              }

Thanks for any help you might have.

kris63
  • 31
  • 2

1 Answers1

0

As you can see in this question swift executes the if-statement if all assignments are properly completed. In your case the assignment let prevFIN = names ["LAST_PP"]["OFL_FINISH"].element?.text will not assign any value for the first entry because the key ["OFL_FINISH"] is not found. So it skips the if statement.

Since your using ?? operator you could just:

let name = names["NAME"].element?.text,
let weight = names ["WEIGHT"].element?.text
let age = names ["AGE"].element?.text
let prevFIN = names ["LAST_PP"]["OFL_FINISH"].element?.text
          
              
tempArray.append(name)
tempArray.append(Int(weight) ?? 0)
tempArray.append(Int(age) ?? 0)            
tempArray.append(Int(prevFIN) ?? 0)

This will assign 0 if the value is not found.

andy meissner
  • 1,202
  • 5
  • 15