Search code examples
swiftxmlxml-parsingswxmlhash

SWXMLHash - Problem accessing to some data


Good day everyone, I need your help :
Ref the xml below which is an extract with only 2 records, I try to access to the <ICAO> element and find '07FA' record to access to its other data.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<AirportDatabase>
   <AptInfo>
      <AirportRecordID>06FA</AirportRecordID>
      <ICAO>06FA</ICAO>
      <TakeoffRwyInfo>
         <RunwayID>27</RunwayID>
         <TORA>2134.5</TORA>
      </TakeoffRwyInfo>
      <LandingRwyInfo>
         <RunwayID>09</RunwayID>
         <LDA>2061.1</LDA>
      </LandingRwyInfo>
   </AptInfo>
   <AptInfo>
      <AirportRecordID>07FA</AirportRecordID>
      <ICAO>07FA</ICAO>
      <TakeoffRwyInfo>
         <RunwayID>05</RunwayID>
         <TORA>1356.7</TORA>
      </TakeoffRwyInfo>
      <LandingRwyInfo>
         <RunwayID>05</RunwayID>
         <LDA>1356.7</LDA>
      </LandingRwyInfo>
   </AptInfo>
...

I tried to write the following code but it doesn't find the record. How can I properly use the filter function ?

let xml = XMLHash.parse(strAirp as String)
let subIndexer = xml["AirportDatabase"]["AptInfo"].filterAll { elem, _ in elem.text == "07FA" }

Then how can I access to [LandingRwyInfo][RunwayID] for this specific record ? I was thinking about something like :

print(subIndexer["LandingRwyInfo"]["RunwayID"])

I thank you in advance !


Solution

  • Using SWXMLHash you could try something like this:

     let subIndexer = xml["AirportDatabase"]["AptInfo"]
         .filterAll { elem, _ in
             elem.innerXML.contains("07FA")
         }
     print("----> subIndexer: \(subIndexer)")
     
     let takeoffRwyInfo = subIndexer["TakeoffRwyInfo"]
     if let runwayId = takeoffRwyInfo["RunwayID"].element?.text {
         print("----> RunwayID: \(runwayId)")
     }