views:

40

answers:

1

Hi all-

I've been working on importing XML into an iPad Core Data application. I have a working NSXMLParser implementation for my files, and have been able to import the simpler (ie attribute-only) elements into Core Data.

Some of the XML dated has nested elements with text, and I'm a bit stumped on how to get Core Data to play nicely in the callback-centric world of NSXML.

If I see a new XML element, I need to insert a new managed object into my context. If I do this in NSXML's didStartElement, I need to preserve a reference to it so that I can store my XML text element when didEndElement is called.

Given that my XML elements are nested, I may have encountered several didStartElements before I encounter a didEndElement, so I need something more than a single object instance to preserve the managed object across callbacks. (Also, I think that insertNewObjectForEntityForName is autoreleased, so I need to retain a copy of the managed object.)

I thought I might build an object stack out of NSMutableArray's addObject and removeLastObject methods, but I wonder if there's something simpler, or I've missed some piece of the big picture here.

Many thanks in advance, Charles

A: 

I've run unto a similar problem, and as you mentioned, ended up using stacks with addObject:, lastObject and removeLastObject:. It parses reasonably quickly.

In my specific case, I had a number of Core Data entities, both with instance variables and to-many relationships to their child elements. I used two stacks, one for the objects, and one for the elements. In my case the parent elements did not have data of their own, ex:

<Parent>
    <Parent_Data1>Foo</ParentData1>
    <Parent_Data2>Bar</ParentData2>
    <Child>
        <Child_Data1>Baz</Child_Data1>
    </Child>
</Parent>

So I had one stack of the entities that contained other entities (Parent and Child in my example), with another containing the keypaths corresponding to the data (Parent_Data1, Parent_Data2 and Child_Data1). When I found the data in parser:foundCharacters I would set it on the topmost entity using setValue:forKeyPath: and pop that when I got to parser:didEndElement:.

Hope that helps.

paxswill
Thanks, paxswill- Nice to know I'm not alone in my thinking. Your point about enclosing entities is also well taken. Best wishes, Charles
cturner