开发者

NSXMLParser Key and Value

开发者 https://www.devze.com 2023-04-13 08:37 出处:网络
I am consuming the following WCF Data Service, I can\'t seem to get the key and value information simultaneously. I understand the NSXMLParser delegate events didStartElement, foundCharacters and didE

I am consuming the following WCF Data Service, I can't seem to get the key and value information simultaneously. I understand the NSXMLParser delegate events didStartElement, foundCharacters and didEndElement. I just can't seem to extract both the key and value information. I am looking to eventually create a NSMutableDictionary with the key as the string d:id and the value as 1 for example. I am new to objective c and struggling my @ss off, lol

<?xml version="1.0" encoding="iso-8859-1" standalone="yes"?>
<entry xml:base="http://localhost:7070/QuickViewMaster.svc/" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
  <id>http://localhost:7070/MyService.svc/configs(1)</id>
  <title type="text"></title>
  <updated>2011-10-17T07:32:39Z</updated>
  <author>
   <name />
 </author>
 <link rel="edit" title="config" href="configs(1)" />
 <category term="TMLIGHT_MasterModel.config" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
  <content type="application/xml">
    <m:properties>
      <d:id m:type="Edm.Int32">1</d:id>
      <d:version_id m:type="Edm.Int32">3</d:version_id>
      <d:name>My Device</d:name>
      <d:svpip>xxx.xxx.xxx.xxx</d:svpip>
      <d:username>test</d:username>
      <d:password>test</d:password>
      <d:serial_number>12345</d:serial_number>
      <开发者_如何学Python;d:short_range>-0100</d:short_range>
      <d:longrange>-000100</d:longrange>
      <d:history_period m:type="Edm.Int32">120</d:history_period>
      <d:controller_type_id m:type="Edm.Int32">5</d:controller_type_id>
      <d:controllertype m:type="Edm.Int32" m:null="true" />
      <d:record_status_id m:type="Edm.Int32">1</d:record_status_id>
      <d:position m:type="Edm.Int32">6</d:position>
      <d:last_run m:type="Edm.DateTime">2011-06-07T12:01:56</d:last_run>
      <d:process_started m:type="Edm.DateTime" m:null="true" />
      <d:process_run m:type="Edm.Int32">0</d:process_run>
      <d:process_error m:type="Edm.Int32">1</d:process_error>
     </m:properties>
  </content>
</entry>

Herewith the code: .h file

#import <UIKit/UIKit.h>

@interface ODataConsumerViewController : UIViewController<NSXMLParserDelegate> {
    NSMutableData *receivedData;
    IBOutlet UITextView *txtvDescription;
    IBOutlet UILabel *label;
    IBOutlet UIButton *parseData;
    NSMutableDictionary *elementsAndValues;
    BOOL foundRecordId;
    NSMutableString *recordId;

    //NSMutableArray *entries;
}

@property (nonatomic, retain) NSMutableData *receivedData;
@property (nonatomic,retain) IBOutlet UITextView *txtvDescription;
@property (nonatomic,retain) IBOutlet UILabel *label;
@property (nonatomic,retain) IBOutlet UIButton *parseData;


- (IBAction)parseData:(id)sender;
- (void)startParsingData;

@end

.m file:

#import "ODataConsumerViewController.h"

@implementation ODataConsumerViewController

@synthesize receivedData;
@synthesize txtvDescription;
@synthesize parseData;
@synthesize label;
//@synthesize enumerator;
//@synthesize aKey;

- (IBAction)parseData:(id)sender
{
    // clear NSMutableData object
    if (receivedData) {
        receivedData = nil;
    }

    //NSString *soapMessage = [NSString stringWithFormat:@"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body><GetDictionary></GetDictionary></SOAP-ENV:Body></SOAP-ENV:Envelope>"];

NSURL *url = [NSURL URLWithString:@"http://192.168.1.55:7070/QuickViewMaster.svc/configs(1)"];

NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url]; 

//NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];             

/*
[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[theRequest addValue: @"urn:MultiEndPointsService/GetDictionary" forHTTPHeaderField:@"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];    
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
 */

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];


if (theConnection) 
{
    // Create the NSMutableData to hold the received data
    receivedData = [[NSMutableData data] retain];

    elementsAndValues = [[[NSMutableDictionary alloc] init] autorelease];
} else 
{
    // Inform the user the connection failed.
    label.text = @"Unable to make connection";
}    

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // Rest the data length if the server reloads
    [receivedData setLength:0];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (receivedData) 
    {
        // Append the new data to receivedData
        [receivedData appendData:data];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // Release the connection, and the data object
    [connection release];
    [receivedData release];

    // Inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);

    // Set label text
    label.text = @"Connection failed!";
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSLog(@"Succeeded! Received %d bytes of data", [receivedData length]);

    // Do something with the data
    // Send data to parser
    [self startParsingData];
    // Release the connection
    [connection release];
}

#pragma mark - View lifecycle


- (void)startParsingData
{
    NSLog(@"parser started");
    // allocate NSXMLParser
    NSXMLParser *dataParser = [[NSXMLParser alloc] initWithData:receivedData];
    // assign delegate to parser
    dataParser.delegate = self;
    // parse data
    [dataParser parse];
    // release parser
    [dataParser release];
    // release data
    [receivedData release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    NSLog(@"elementName: %@",elementName);

    NSMutableString *recordId = [[NSMutableString alloc] init];

    foundRecordId = [elementName isEqualToString:@"d:id"];

}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    NSLog(@"foundCharacters: %@",string);

    if (foundRecordId) {
        [recordId appendString:string];
    }

}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
{
    if (foundRecordId) {
        NSLog(@"didEndElement = %@", recordId);
        foundRecordId = NO;
    }
}


- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {

    NSLog(@"Parsing error");

    // Notify user of parser error
    label.text = @"Parsing error!";

}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad 
{
    label.text = recordId;


    [super viewDidLoad];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}

@end


d is your namespaceURI and id is your elementName in that XML file.

Try replacing:

foundRecordId = [elementName isEqualToString:@"d:id"];

with:

foundRecordId = [namespaceURI isEqualToString:@"d"] && [elementName isEqualToString:@"id"];

To store element and its value in a dictionary you should do the following:

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:    (NSString *)namespaceURI qualifiedName:(NSString *)qName 
{
    if (foundRecordId) {
        NSLog(@"didEndElement = %@", recordId);

        // set the dictionary entry
        [elementsAndValues setObject:recordId forKey:elementName];

        foundRecordId = NO;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号