0

Playing around with SWXMLHash, I am trying to pull out an element and then get its info. My xml file is large and I'd like to split up the parsing in smaller functions.

For example, this is from the GitHub page:

let xml = """
<root>
   <catalog>
       <book><author>Bob</author></book>
       <book><author>John</author></book>
       <book><author>Mark</author></book>
   </catalog>
</root>
"""

self.parsedXML = SWXMLHash.parse(xml)
        
let name1 = parsedXML?["root"]["catalog"]["book"][0]["author"].element?.text
let name2 = parsedXML?["root"]["catalog"]["book"][1]["author"].element?.text
let name3 = parsedXML?["root"]["catalog"]["book"][2]["author"].element?.text

This correctly results in "Bob, John, Mark"

But if I first pull out the catalog, all names are nil:

let catalog = parsedXML?["root"]["catalog"]
        
let name1 = catalog?["book"][0]["author"].element?.text // nil
let name2 = catalog?["book"][1]["author"].element?.text // nil
let name3 = catalog?["book"][2]["author"].element?.text // nil

Why is this, what am I missing?

koen
  • 5,383
  • 7
  • 50
  • 89
  • Hi @koen, I'm not sure what is going on - it seems to work for me in an Xcode playground. See https://gist.github.com/drmohundro/960cde2ed8d0568b128543c6f039d817. Maybe a repository with a repro would help? – David Mohundro Aug 24 '20 at 16:35
  • Hi @DavidMohundro - glad to hear that it should work. This was some test code inside a larger project I am working on. So I'm sure something else is going on somewhere. Only thing I can think off right now is that the parsing is happening on a background thread after downloading the data - could that be related? In the meantime, I switched to using `XMLIndexerDeserializable` which seems to work nicely so far. – koen Aug 24 '20 at 16:44
  • 1
    I don't _think_ a background thread should matter, unless you're also doing lazy loading, because it parses the XML into an in-memory structure on the initial `parse` call. At that point, passing an indexer around is just a subset of the parsed data. – David Mohundro Aug 24 '20 at 18:04
  • Ah yes, I was using `shouldProcessLazily` at one moment. And was able to reproduce this in a small single view project with `shouldProcessLazily` set to `true`. Now I see the correct names for name1 and name2, but name3 is still nil. With `shouldProcessLazily` set to false, all three are ok. So that must have been it. Thanks for the pointer and for writing `SWXMLHash`. – koen Aug 24 '20 at 21:16

0 Answers0