Parsing XML Data in Core Data
I am trying to extract data from an online xml file and put it in my master data.
I can successfully retrieve the data and I can even put it inside the main data, but it seems that only the last received channel is saved.
Here is an example xml file I am trying to extract.
Parser code example:
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if (elementName as NSString).isEqualToString("question") {
if !xml_tmp1.isEqual(nil) {
elements.setObject(xml_tmp1, forKey: "text")
}
if !xml_tmp2.isEqual(nil) {
elements.setObject(xml_tmp2, forKey: "answer0")
}
if !xml_tmp3.isEqual(nil) {
elements.setObject(xml_tmp3, forKey: "answer1")
}
if !xml_tmp4.isEqual(nil) {
elements.setObject(xml_tmp4, forKey: "answer2")
}
if !xml_tmp5.isEqual(nil) {
elements.setObject(xml_tmp5, forKey: "answer3")
}
tmp_xml.addObject(elements)
}
}
Sample master data code:
func temp_func() {
var n: Int = tmp_xml.count
var i: Int = 0
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context: NSManagedObjectContext = appDel.managedObjectContext!
var tmp = NSEntityDescription.insertNewObjectForEntityForName("Questions", inManagedObjectContext: context) as! NSManagedObject
while (i != br) {
tmp.setValue(tmp_xml.objectAtIndex(i).valueForKey("text"), forKey: "question")
tmp.setValue(tmp_xml.objectAtIndex(i).valueForKey("answer0"), forKey: "answer_1")
tmp.setValue(tmp_xml.objectAtIndex(i).valueForKey("answer1"), forKey: "answer_2")
tmp.setValue(tmp_xml.objectAtIndex(i).valueForKey("answer2"), forKey: "answer_3")
tmp.setValue(tmp_xml.objectAtIndex(i).valueForKey("answer3"), forKey: "answer_4")
i++
}
context.save(nil)
}
Basically, I should get three new records in my master data, but only the last one is kept (question 15 * 7).
+3
source to share
1 answer
I think U will just create one record in U-main data and U setValue than save it. Thus, only the last entry is saved in the master data. U can just create a record in the while loop. as seen, it can work?
func temp_func() {
var n: Int = tmp_xml.count
var i: Int = 0
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context: NSManagedObjectContext = appDel.managedObjectContext!
while (i != br) {
var tmp = NSEntityDescription.insertNewObjectForEntityForName("Questions", inManagedObjectContext: context) as! NSManagedObject
tmp.setValue(tmp_xml.objectAtIndex(i).valueForKey("text"), forKey: "question")
tmp.setValue(tmp_xml.objectAtIndex(i).valueForKey("answer0"), forKey: "answer_1")
tmp.setValue(tmp_xml.objectAtIndex(i).valueForKey("answer1"), forKey: "answer_2")
tmp.setValue(tmp_xml.objectAtIndex(i).valueForKey("answer2"), forKey: "answer_3")
tmp.setValue(tmp_xml.objectAtIndex(i).valueForKey("answer3"), forKey: "answer_4")
i++
}
context.save(nil)
}
+2
source to share