NSXMLParser键和值

时间:2011-10-17 13:58:52

标签: objective-c nsxmlparser

我正在使用以下WCF数据服务,我似乎无法同时获取密钥和值信息。我理解NSXMLParser委托事件didStartElement,foundCharacters和didEndElement。我似乎无法提取关键和价值信息。我希望最终创建一个NSMutableDictionary,键为字符串d:id,值为1。我是目标c的新手并且正在努力解决我的@ss,大声笑

<?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>
      <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>

此处代码:.h文件

#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文件:

#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

1 个答案:

答案 0 :(得分:1)

d是您的namespaceURIid是您在该XML文件中的elementName

尝试更换:

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

使用:

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

要将元素及其值存储在字典中,您应该执行以下操作:

-(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;
    }
}