SDeveloper
SDeveloper

Reputation: 1

Parsing XML with attributes in IOS

I have an XML file which I want to parse in objective-C but can't find a better way...

<record xmlns="http://www.loc.gov/MARC21/slim">
  <datafield ind1=" " ind2=" " tag="020">
    <subfield code="z">1234567890</subfield>
  </datafield>
  <datafield ind1="1" ind2=" " tag="100">
    <subfield code="a">Ashton-Good, Donna.</subfield>
  </datafield>
  <datafield ind1="1" ind2="0" tag="245">
    <subfield code="a">Eazee skating</subfield>
    <subfield code="h">[videorecording] :</subfield>
    <subfield code="b">the basics of ice skating for beginners of all ages /</subfield>
    <subfield code="c">Donna Ashton-Good.</subfield>
  </datafield>
  <datafield ind1="3" ind2=" " tag="246">
    <subfield code="a">Easy skating</subfield>
  </datafield>
  <datafield ind1=" " ind2=" " tag="260">
    <subfield code="a">[S.l.] :</subfield>
    <subfield code="b">D. Ashton-Good,</subfield>
    <subfield code="c">c1999.</subfield>
  </datafield>
</record>

This XML contains tag and code which needs to be parsed to get the data. Please help me in parsing this XML.

Upvotes: 0

Views: 927

Answers (2)

IronManGill
IronManGill

Reputation: 7226

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 filled with all of your category name.

Hope this helps :)

Upvotes: 1

Matthias
Matthias

Reputation: 8180

You can use the NSXMLParser. If you want to use XPath,there are external libraries, e.g., TouchXML.

Upvotes: 0

Related Questions