0

I try to parse following XML file:

<MesPar DH="HBCHa" StrNr="2416" Typ="10" Var="10">
    <Name>Aabach - Hitzkirch</Name>
    <Datum>11.11.2013</Datum>
    <Zeit>18:00</Zeit>
    <Wert>2.02</Wert>
    <Wert dt="-24h">1.93</Wert>
</MesPar>

<MesPar DH="HBCHa" StrNr="2312" Typ="02" Var="00">
    <Name>Aach - Salmsach</Name>
    <Datum>11.11.2013</Datum>
    <Zeit>18:00</Zeit>
    <Wert>406.47</Wert>
    <Wert dt="-24h">406.64</Wert>
</MesPar>

I will read the element values if the attribute "StrNr" is equal to "2416". My code is:

NSURL *url = [NSURL URLWithString:@"http://www.hydrodaten.admin.ch/lhg/SMS.xml"];
NSData *webData = [NSData dataWithContentsOfURL:url options:NSUTF8StringEncoding error:nil];
TFHpple *parser = [TFHpple hppleWithData:webData isXML:YES];
NSString *xPathQuery = @"//AKT_Data/MesPar";
NSArray *arrayPaser= [parser searchWithXPathQuery:xPathQuery];

NSMutableArray *arrayName = [[NSMutableArray alloc] initWithCapacity:0];
NSMutableArray *arrayDatum = [[NSMutableArray alloc] initWithCapacity:0];
NSMutableArray *arrayWertDt24h = [[NSMutableArray alloc] initWithCapacity:0];


for (TFHppleElement *element in arrayPaser) {
    if ([[element firstChild] content]!=nil) {
        NSDictionary *attribute=[element attributes];

        NSString *string= [NSString stringWithFormat:@"%@",[attribute valueForKey:@"StrNr"]];

        if ([string isEqualToString:@"2416"]) {

            arrayName addObject:[element ??????];
            arrayDatum addObject:[element ?????];
            arrayWertDt24h addObject:[element ????];
        }

I don't know how i get the values from the element?

1 Answer 1

1

I have a solution that involves using the built in NSXMLParser and a couple NSXMLParserDelegate methods.

Let's first subclass NSObject and create a parser class. Here is the .h:

#import <Foundation/Foundation.h>

@interface XMLParser : NSObject

- (id)initWithData:(NSData *)data;
- (BOOL)parse;

@end

Here you can see that we will feed this object the data you'd like to parse and after that is done we can tell it to parse. The parse method is simply a wrapper around the NSXMLParser parse method that you will see in a moment.

A class extension is where we will add the private properties we will use to manage the data we are parsing. It appears as follows:

@interface XMLParser ()
<NSXMLParserDelegate>

@property (nonatomic, strong) NSData *data;
@property (nonatomic, strong) NSXMLParser *parser;
@property (nonatomic, strong) NSMutableDictionary *objectDict;
@property (nonatomic, strong) NSMutableString *elementDataString;
@property (nonatomic, strong) NSMutableDictionary *wertTwo;
@property (nonatomic, assign, getter = isParsingWertTwo) BOOL parsingWertTwo;

@end

The data and parser properties are self explanatory. The objectDict property is what we will use to store the data you are looking to parse from this XML. The elementDataString will hold the characters the parser finds in between the element tags. We have a wertTwo property and a flag to indicate when we are parsing the second Wert element. This is so we can make sure to grab the attributes from this second Wert element.

The beginning of the implementation appears as follows:

@implementation XMLParser

- (id)initWithData:(NSData *)data
{
    self = [super init];
    if (self) {
        self.data = data;
        self.parser = [[NSXMLParser alloc] initWithData:data];
        self.parser.delegate = self;
        self.objectDict = [@{} mutableCopy];
        self.wertTwo = [@{} mutableCopy];
    }
    return self;
}

- (BOOL)parse
{
    return [self.parser parse];
}

As you can see from the initializer, we set up the objects we need along with the data and parser to do the actual parsing. The parse method as I mentioned simply wraps the parse method of the NSXMLParser class. It actually returns a BOOL and that is why I chose to return it here as well. We set self as the delegate of the parser so we have to implement a few of the methods in the delegate protocol in order to obtain the necessary data. The delegate methods appear as follows:

#pragma mark - NSXMLParserDelegate

- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
    attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:@"MesPar"]) {

        // Get the value from the attribute dict of the MesPar element
        NSString *value = attributeDict[@"StrNr"];

        // Compare whether the value is equal to the desired value
        if ([value isEqualToString:@"2416"]) {

            // if the value is equal, add the attribute dict to the object dict
            [self.objectDict addEntriesFromDictionary:attributeDict];

            return;
        }
    }

    // If the element is Wert AND there is an attribute named dt we know this is the second Wert element
    if ([elementName isEqualToString:@"Wert"] && attributeDict[@"dt"]) {

        // add the attribute element to the wertTwo dict
        [self.wertTwo addEntriesFromDictionary:attributeDict];

        // Set the parsing flag to YES so we know where we are in the delegate methods
        self.parsingWertTwo = YES;

        return;
    }
}

- (void)parser:(NSXMLParser *)parser
 didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
{
    // if this is the Name element, set the element data in the object dict
    if ([elementName isEqualToString:@"Name"]) {
        [self.objectDict setObject:[self.elementDataString copy] forKey:@"name"];

        // set the data to nil since it will be reset by a delegate method for the next element
        self.elementDataString = nil;

        return;
    }

    if ([elementName isEqualToString:@"Datum"]) {
        [self.objectDict setObject:[self.elementDataString copy] forKey:@"datum"];

        // set the data to nil since it will be reset by a delegate method for the next element
        self.elementDataString = nil;

        return;
    }

    if ([elementName isEqualToString:@"Zeit"]) {
        [self.objectDict setObject:[self.elementDataString copy] forKey:@"zeit"];

        // set the data to nil since it will be reset by a delegate method for the next element
        self.elementDataString = nil;

        return;
    }


    if ([elementName isEqualToString:@"Wert"]) {

        // Checks to see if this is the Wert element AND that we are parsing the second element
        if (self.isParsingWertTwo) {
            [self.wertTwo setObject:[self.elementDataString copy] forKey:@"wertTwoString"];

            // set the wertTwo dict for the key wertTwo in the object dict
            // this allows us to pull out this info for the key wertTwo and includes the attribute of dt along with the elementDataString
            [self.objectDict setObject:[self.wertTwo copy] forKey:@"wertTwo"];

            // set the data to nil since it will be reset by a delegate method for the next element
            self.elementDataString = nil;

            return;
        }
        else{
            [self.objectDict setObject:[self.elementDataString copy] forKey:@"wertOne"];

            // set the data to nil since it will be reset by a delegate method for the next element
            self.elementDataString = nil;

            return;
        }
    }
}

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    // You do not have to implement this but if you'd like here you can access `self.objectDict` which should have a representation of your XML you're looking to parse
}


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    // Append the foundCharacters (in between the element tags) to the data string
    [self.elementDataString appendString:string];
}

The code is commented on what is actually happening but in short, the parser is notifying the delegate, self in this instance when certain things are happening such as when it comes across an element or when it is finding characters. One thing to keep in mind is that the elementDataString property needs to be lazily loaded and we do that like so:

// lazy loads the elementDataString if it is nil
// it will be set to nil after each time it is set in a dict
// this is why we copy it when we add it to the dict
- (NSMutableString *)elementDataString
{
    if (!_elementDataString) {
        _elementDataString = [NSMutableString string];
    }
    return _elementDataString;
}

There are several things I have not addressed such as errors in parsing or additional delegate methods that you may be interested in. This is one particular solution that makes use of built in classes rather than relying on a 3rd party library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.