how to parse xml for ios development - iphone

So I know how to parse some XML structures but I am currently trying to parse this specific xml structure thats a bit different to what I am used to.
normally I would parse something like
<xml>
<data>
<name>Forrest</name>
<age>25</name>
<username>forrestgrant</username>
</data>
</xml>
But now I'm working with some xml like so..
<xml>
<data name="Forrest" age="25" username="forrestgrant" />
<other value="6" />
</xml>
how do I access those variables when they are structured like this?
This is how I would normally approach this task, which is baised of searching for the title tags and getting the data from each one.. however I am now trying to figure out how to parse this other style of xml.
- (void)startTheParsingProcess:(NSData *)parserData
{
[myDataArray release]; // clears array for next time it is used.
myDataArray = [[NSMutableArray alloc] init]; //initalizes the array
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:parserData]; //incoming parserDatapassed to NSXMLParser delegate which starts parsing process
[parser setDelegate:self];
[parser parse]; //Starts the event-driven parsing operation.
[parser release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqual:#"item"]) {
// NSLog(#"Found title!");
itemString = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[itemString appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqual:#"item"]) {
//NSLog(#"ended title: %#", itemString);
[myDataArray addObject:itemString]; //this is where i pass the values over to my array.
[itemString release];
itemString = nil;
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
// Passes myDataArray to the method that will sort and display the array into a uitableview.
[self startSortingTheArray:myDataArray];
}
any help would be greatly appreciated..

The xml data above provides the data as attributes on the xml element.
This callback method gives you access to the attributes as a dictionary of key values (attributeDict).
(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
NSLog the dictionary out in that method to see the values:
NSLog(#"attributes: %#", attributeDict);

In your didStartItem: method, the attributes dictionary will contain values for all the XML attributes.

Related

How to parse the xml file have same tag name using nsxmlparser?

How do I parse this type of XML using NSXMLParser
<category> <categoryName> userName</categoryName> <categoryName>password</categoryName><category>
Declare array and a string in h file like:
NSMutableArray *aryCategory;
NSString *strCategroyName;
in .m file for starting Parser use:
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:yourData]; // your data will be instance of NSData or NSMutableData
parser.delegate = self;
[parser parse];
this will be done once you get your xml data. For handling result you can use NSXMLParserDelegate as follows:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:#"category"]) {
aryCategory = [[NSMutableArray alloc] init];
strCategroyName = #"";
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
strCategroyName = [NSString stringWithFormat:#"%#%#", strCategroyName, string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"categoryName"]) {
[aryCategory addObject:strCategroyName];
strCategroyName = #"";
}
}
Now you will have your array fill with all of your category name.
Hope this helps :)
Write the <category> in didStart and didEnd elements which are the parser's delegates.

How to parse the xml using nsxmlparser with same names of multiple nodes in iphone programming?

How can I parse using NSXMLParser if I need all the images,
<title>Title</title>
<description>my description is here </description>
<images>
<image>http://www.sosmoths.com/mothImages/800px-Tineola.bisselliella.7218.jpg</image>
<image>http://www.sosmoths.com/mothImages/800px-Tineola.bisselliella.mounted.jpg</image>
<image>http://www.sosmoths.com/mothImages/800px-XN_Tineola_bisselliella_1.jpg</image>
<image>http://www.sosmoths.com/mothImages/Tineola_bisselliella.JPG</image>
</images>
There are more nodes like title, description, so how to parse such xml, I am confused about image nodes, I am thinking to use NSMutableArray for this, but still not clear to do code?
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:"<image>"])
{
[imagearray addObject:imageurl];
}
}
Before this you need to find the element name is and then do above code.This may help you.
use this it work
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
NSLog(#"%#",elementName);
if([elementName isEqualToString:#"moths"]){
mytblarray=[[NSMutableArray alloc] init];
} else if([elementName isEqualToString:#"moth"]){
tmpdic=[[NSMutableDictionary alloc] init];
}
else if([elementName isEqualToString:#"images"]){
imgArray=[[NSMutableArray alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if(tmpstr!=nil && [tmpstr retainCount]>0){ [tmpstr release]; tmpstr=nil; }
tmpstr=[[NSString alloc] initWithString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if([elementName isEqualToString:#"moth"]){
[mytblarray addObject:tmpdic];
[tmpdic release];
}if([elementName isEqualToString:#"images"]){
[tmpdic setValue:imgArray forKey:elementName];
}
else if([elementName isEqualToString:#"image"]){
[imgArray addObject:tmpstr];
}
}
take dictionary in initWithData: methode
Take values as key like title, description
in didStartElement method, in images tag alloc image_array
in didEndElement method, in image tag add your data(here your image link) to image_array
now in didEndElement method, in images tag add that array to your main dictionary as key images
that's all.....

Using dictionaries with XML (iphone/iOs)

I want to parse data from a xml file. This is working so far, but I don't find the correct way to get data from the dictionary.
My parser looks as follows
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"Placemark"]) {
placemarkData = [[NSMutableDictionary alloc] init];
currentTitle = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([currentElement isEqualToString:#"name"] || [currentElement isEqualToString:#"address"] || [currentElement isEqualToString:#"coordinates"])
[currentTitle appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"Placemark"]) {
[placemarkData setObject:currentTitle forKey:currentElement];
[Placemarks addObject:[placemarkData copy]];
NSLog(#"adding story: %#", currentElement);
}
As you can see. The data is stored in a dictionary, and this dictionary is store in an array. Only problem is... the key for dictionary is always coordinates. This look kinda logical to me... but I don't find the logic to implement it the right way. Can somebody have a look?
Thnx in advance!
When you fill a dictionary, you set objects for keys. To get an object from a dictionay, you need to have the key. And I think that is your problem.
To list the keys in your dictionary, you can use a keyEnumerator:
NSEnumerator *enumerator = [myDictionary keyEnumerator];
id key;
while ((key = [enumerator nextObject])) {
/* code that uses the returned key */
NSString *theElement = key;
NSLog(#"Element: %#", theElement);
}
With this code, you will list all the keys. To find the object with the key, you use [myDictionary objectForKey:key];. If you know the elements in your XML you can access them with this line.
I think the problem you are facing is because of the logic you used in
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"Placemark"]) {
placemarkData = [[NSMutableDictionary alloc] init];
currentTitle = [[NSMutableString alloc] init];
}
}
method, i.e. allocating the placemarkData that will work fine if element Placemark is encountered first time but for the next iteration there will be problem, follow this idea and see the response on to the console, I am sure that you will find the solution.
come back if any doubt or query in that.

NSXMLParsing for particular tag value [duplicate]

I have an XML file that looks like this:
<country>
<routes>
<SourceCountry>Ireland</SourceCountry>
<SourcePort>Larne</SourcePort>
<DestinationCountry>UK</DestinationCountry>
<DestinationPort>Troon </DestinationPort>
</routes>
<routes>
<SourceCountry>Ireland</SourceCountry>
<SourcePort>Larne</SourcePort>
<DestinationCountry>UK</DestinationCountry>
<DestinationPort>Cairnryan </DestinationPort>
</routes>
<routes>
<SourceCountry>Ireland</SourceCountry>
<SourcePort>Belfast</SourcePort>
<DestinationCountry>UK</DestinationCountry>
<DestinationPort>Birkenhead </DestinationPort>
</routes>
<routes>
<SourceCountry>Ireland</SourceCountry>
<SourcePort>Belfast</SourcePort>
<DestinationCountry>Belgium</DestinationCountry>
<DestinationPort>Heysham </DestinationPort>
</routes>
<routes>
<SourceCountry>Belgium</SourceCountry>
<SourcePort>Warrenpoint</SourcePort>
<DestinationCountry>UK</DestinationCountry>
<DestinationPort>Heysham </DestinationPort>
</routes>
I want parse particular data for <SourceCountry> == Ireland and <DestinationCountry> == UK. How can I do this?
Use NSXMLParser
implement the delegate for this class ... <NSXMLParserDelegate>
implement the methods for this parser...
YOU will need the following methods..
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
You can read this tutorial; it is simple to use.
This may help
Accessing specific child elements when parsing RSS with NSXMLParser
You need to use XML parser, Use NSXMLParser to parse you data.
Below is the apple sample code of ImageMap in which they have used the NSXMLParser to parse XML content.
http://developer.apple.com/library/mac/#samplecode/ImageMap/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009015
Try this . . .
int element=0;
[self parseXMLFileAtURL:filepath];
following methods are the delegates of NSXMLParser
- (void)parseXMLFileAtURL:(NSString *)URL
{
NSURL *xmlURL = [NSURL fileURLWithPath:URL];
parser = [[ NSClassFromString(#"NSXMLParser") alloc] initWithContentsOfURL:xmlURL];
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
NSLog(#"found file and started parsing");
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if(([elementName compare:#"SourceCountry"])==NSOrderedSame)
element=1;
if(([elementName compare:#"SourcePort"])==NSOrderedSame)
element=2;
if(([elementName compare:#"DestinationCountry"])==NSOrderedSame)
element=3;
if(([elementName compare:#"DestinationPort"])==NSOrderedSame)
element=4;
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (element==1)
{
[TotalXMLArray addObject:string];
element=0;
}
if (element==2)
{
[TotalXMLArray addObject:string];
element=0;
}
if (element==3)
{
[TotalXMLArray addObject:string];
element=0;
}
if (element==4)
{
[TotalXMLArray addObject:string];
element=0;
}
}

How do I parse this SOAP response in my iPhone application?

I am getting SOAP response and when parsing the response I am getting this: (As you can see from result which is currently stored as NSString is NSLoged itself contain xml format data)
<Menus>
<Table1>
<Restaurant_Name>CHICK-FIL-A</Restaurant_Name>
<Restaurant_id>2748</Restaurant_id>
<Phone>(404) 371-1466</Phone>
<billing_city>DECATUR</billing_city>
<billing_state>GA</billing_state>
<billing_zip_code>30030</billing_zip_code>
<billing_addr1>105 EAST TRINITY PLACE</billing_addr1>
</Table1>
</Menus>
The Code for the above generated response:
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
if([elementName isEqualToString:#"GetMenusByZipCodeResult"])
{
if(!soapResults)
{
soapResults = [[NSMutableString alloc] init];
}
recordResults = TRUE;
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if(recordResults)
{
[soapResults appendString:string];
}
//NSLog(#" soap: %#", soapResults);
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
{
if([elementName isEqualToString:#"GetMenusByZipCodeResult"])
{
NSLog(#"soapResult FINAL : %#",soapResults);
recordResults = FALSE;
result.text = soapResults;
[soapResults release];
soapResults = nil;
}
}
The above mention data is result of soapResult.
How to read this data? I tried to reparse it but it is not helping.
Please help me.
If you want a simple XML to NSDictionary converter (including the text nodes), check out http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/
Use an XML parser like NSXMLParser
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html