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
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>
<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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
d
是您的namespaceURI
,id
是您在该 XML 文件中的elementName
。尝试将:替换
为:
要将元素及其值存储在字典中,您应该执行以下操作:
d
is yournamespaceURI
andid
is yourelementName
in that XML file.Try replacing:
with:
To store element and its value in a dictionary you should do the following: