I am parsing a XML file with a format of:
**NOTE: This is a very simplified version of the XML. There are 11 divisions, and 87 departments total
<division>
<name> Sciences </name>
<departments>
<department>
<name> Computer Science </name>
</department>
<department>
<name> Biology </name>
</department>
<department>
<name> Chemistry </name>
</department>
</department>
</division>
What I am hoping to do is display this info in a UITableView, with Division names as the Sections, and the department names within each appropriate section.
I have a NSDictionary called divisionDict which I want to store NSArrays for each division; containing the departments. I also have a NSMutableArray called departmentArray, which contains each of the departments. So essentially, I want a divisionDict filled with departmentArrays.
Here is my code for parsing the XML, which works perfect, I am just having trouble storing separate arrays in the dictionary. When it goes through the parse now, and I try to print out the elements in the array with key "Sciences", it prints the departments for every division, not just the Sciences.
if(node_divisions)
{
node_division = [TBXML childElementNamed:#"division" parentElement:node_divisions];
while (node_division)
{
node_divisionName = [TBXML childElementNamed:#"name" parentElement:node_division];];
node_departments = [TBXML childElementNamed:#"departments" parentElement:node_division];
node_department = [TBXML childElementNamed:#"department" parentElement:node_departments];
divisionName = [TBXML textForElement:node_divisionName];
while(node_department)
{
node_departmentName = [TBXML childElementNamed:#"name" parentElement:node_department];
departmentName = [TBXML textForElement:node_departmentName];
//add the department name to the array
[departmentArray addObject:departmentName];
node_department = node_department->nextSibling;
}
//add the departmentArray to the dictionary, using the division name as the key
[divisionDict setObject:departmentArray forKey:divisionName];;
node_division = node_division->nextSibling;
}
}
Any help is greatly appreciated!!! I know its something simple I am missing probably but I have been looking at this for too many hours now and I just can't see it. If you need any other info, just let me know, I tried to explain everything in detail.
Also, here is a picture that hopefully helps show what I am trying to describe:
http://i.stack.imgur.com/a9nSb.png
It looks like you're adding all of the departments for each division to the same array. I think you just need to create a new array for each division in the loop:
while (node_division)
{
departmentArray = [NSMutableArray array]; //add this line
Related
I'm sorry for this (probably very) noob question, but i've been asked about this and can't see what's wrong (i'm java tought..)
This is what I have, data is loaded via JSON:
NSDictionary *myvalues = [myres objectForKey:#"0"];
this is the content if I output via NSLog:
({id = "1a";myval = 5;},
{id = "2b";myval="24.6";})
how do I iterate through myvalues and how do I get the values id and myval? Something like this i'm getting stuck:
for (NSArray* myvals_array in myvalues)
First it looks like the returned value is an Array, the content inside of the parentheses() denotes this. So I would try and set it as such instead of a Dictionary. Then you can enumerate through the array of dictionary's and get each dictionary inside:
for (id object in myvalues) {
NSDictionary *currentObject = (NSDictionary*)object;
NSString *myID = [currentObject valueForKey:#"id"];
NSString *myValue = [currentObject valueForKey:#"myval"];
NSLog(#"ID:%# VALUE:%#",myID,myValue);
}
This will enumerate through the array and create a dictionary for each entry, then get the values for each of the two elements inside. I just NSLog() them here but you can do whatever you want with the values.
I would like to create an NSDictionary or (NSArray) full of NSDictionary objects for each station in the following XML:
<stations lastUpdate="1328986911319" version="2.0">
<station>
<id>1</id>
<name>River Street , Clerkenwell</name>
<terminalName>001023</terminalName>
<lat>51.52916347</lat>
<long>-0.109970527</long>
<installed>true</installed>
<locked>false</locked>
<installDate>1278947280000</installDate>
<removalDate/>
<temporary>false</temporary>
<nbBikes>12</nbBikes>
<nbEmptyDocks>7</nbEmptyDocks>
<nbDocks>19</nbDocks>
</station>
... more...
<station>
<id>260</id>
<name>Broadwick Street, Soho</name>
<terminalName>003489</terminalName>
<lat>51.5136846</lat>
<long>-0.135580879</long>
<installed>true</installed>
<locked>false</locked>
<installDate>1279711020000</installDate>
<removalDate/>
<temporary>false</temporary>
<nbBikes>12</nbBikes>
<nbEmptyDocks>4</nbEmptyDocks>
<nbDocks>18</nbDocks>
</station>
...
</stations>
What's the best way to achieve this? Right now I have an NSDictionary with one object and one key - "stations", but I want the NSDictionary (or NSArray) of NSDictionarys.
I'm using an XML parser by Troy Brant - http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/
I'm guessing it's going to involve some looping of some sort but I'm not really sure how to approach this problem. Any help or pointers in the right direction would be much appreciated.
Thanks.
I also use the XMLReader it is very easy to understand
I have looked at your xml, and I am assuming you wanted to use the array of station tags.
Here is my solution:
NSDictionary *dictXML= [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
NSArray *arrStation = [[dictXML objectForKey:#"stations"] objectForKey:#"station"];//this would return the array of station dictionaries
Now that you have the array of station tags you can do what you want for example displaying all id:
for(int i=0;i<[arrStation count];i++){
NSDictionary *aStation = [arrStation objectAtIndex:i];
NSLog(#"id = %#",[aStation objectForKey:#"id"]);
}
also you can write less code using the fast enumeration loop:
for(NSDictionary *aStation in arrStation){
NSLog(#"id = %#",[aStation objectForKey:#"id"]);
}
hope that helps :)
The best way would be to create subclasses of NSObject that map to each tag. That would be way more cleaner than using Dictionaries and Arrays.
hy everyone,
i really need a helping hand here.
here is my problem:
i have an array with objects which each has two attributes:
1 is an NSSTring name
2 is an NSSNumber price
now i want to run through the array and add all the values to a new string:
the problem is i need the following output.
name (from object 1) : price (from object 1) then new line (\n)
name (from object 2) : price (from object 2) then new line (\n) ... and so on...
would be great if someone could help me here.
with kind regards, thomas
Try this:
// This contains your objects with names and prices;
NSArray *productArray;
...
// |listOfProducts| will be your string with all names and prices.
NSMutableString *listOfProducts = [[NSMutableString alloc] init];
// Build the list of products
for (Product *product in productArray) {
[listOfProducts appendFormat:#"%#: $%0.2f\n", product.name, product.price];
}
I need to select stories from a NSArray of XML by matching a string from an XML element against a list of strings in another NSArray
The XML contains stories, each story has three criteria, say 'Fruit', 'Veg', 'Spice', each containing a single phrase. A sample story might look like:
<story>
<title>I love cooking</title>
<fruit>Oranges</fruit>
<veg>Cauliflower</veg>
<spice>Mixed spice</spice>
<blurb>losts of text and stuff....</blurb>
</story>
I have three dictionaries of key/value pairs in a NSMutableDictionary generated from a pList
<Fruit:dictionary>
'Ripe bananas' : 1
'Green bananas' : 0
<Veg:dictionary>
'Green beans' : 1
'Cauliflower' : 0
<Spice:dictionary>
'Nutmeg' : 1
'Mixed spice' : 0
I don't know what the keys will be, and I need to match the tag in the story against the keys.
i.e. story fruit tag:'Ripe bananas' MATCHES 'Ripe bananas' in list of fruit keys
I can build three arrays of the keys using
NSMutableDictionary *fruitTagsDict = [prefsDictionary objectForKey:#"Fruits"];
NSArray *fruitTags = [fruitTagsDict allKeys];
I loop through the story XML extracting a tag
for (id myArrayElement in storyArray) {
NSString *fruitString = [NSString stringWithString:[myArrayElement fruit]];
//BOOL isTheObjectThere = [issueTags containsObject:fruitString];
NSString *vegString = [NSString stringWithString:[myArrayElement veg]];
NSString *spiceString = [NSString stringWithString:[myArrayElement spice]];
//if ([[fruitTags objectAtIndex:row] isEqualToString:fruitString]) {
//NSLog(#"Yo %#", fruitString);
// ADD TO A NEW ARRAY OF MATCHING STORIES
//}
// Fails because row is undeclared
}
Then I start to glaze out.
The isTheObjectThere line produces nil then crashes at end of loop
I've looked at:
Filter entire NSDictionaries out of NSArray based on multiple keys
Making the Code check to see if the Text in a Text box matches any of the Strings in an NSArray
It seems predicate is the answer but frankly I getting confused.
What I need to do in metacode
repeat with stories
if storyFruitTag is in fruitTagArray
OR storyVegTag is in vegTagArray
OR storySpiceTag is in spiceTagArray
Add to new array of matching stories
Hopefully I've explained enough to get some pointers, I looked into NSMutableSet and Intersect (Xcode: Compare two NSMutableArrays) but the power of too much information got to me
Here's a simple way to determine whether there are matches using key paths:
if ([prefsDict valueForKeyPath:[NSString stringWithFormat:#"Fruit.%#", storyFruitTag]] ||
[prefsDict valueForKeyPath:[NSString stringWithFormat:#"Veg.%#", storyVegTag]] ||
[prefsDict valueForKeyPath:[NSString stringWithFormat:#"Spice.%#", storySpiceTag]]) {
// one of the story's tags matches a key in one of the corresponding dictionaries
}
I have implemented demo using TouchXml parser.Its working fine.But I want to parse xml like below.
example:
<Root>
<tag1></tag1>
<tag2>
<temp1></temp1>
<temp2></temp2>
<temp3></temp3>
</tag2>
<tag3></tag3>
</Root>
How to parse this type of example?
TouchXML is nice and easy to use. First you'll want to parse the document:
NSError *theError = NULL;
CXMLDocument *theXMLDocument = [[[CXMLDocument alloc] initWithXMLString:input options:0 error:&theError] autorelease];
You can then query the structure of your document using XPath. For example to extract the Root element you might do this:
NSArray *foundRoots = [theXMLDocument nodesForXPath:#"//Root" error:&theError];
CXMLElement *root = [foundRoots objectAtIndex:0];
(You often get arrays back, so in your case you can just take the first element, assuming it exists in the document)
You can also do things like get all the child elements of an element. So if we wanted to get all the tags we could this:
NSArray *children = [root children];
Or we could get a tag with a particular name:
NSArray *tag1 = [root elementsForName:#"tag1"];
(Again you get an array, so do the right thing and check)
Does your data conform to any schema?