dom属性值解析

//dom属性值解析

//在类文件里

//自定义初始化方法在该方法中开始准备解析

- (id)initWithData:(NSData*)data {

if(self = [super init]) {

//dom属性值解析

NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];

parser.delegate = self;

[parser parse];

}

return self;

}

#pragma mark --- NSXMLParserDelegate

//开始解析

- (void)parserDidStartDocument:(NSXMLParser *)parser {

NSLog(@"---开始解析----");

_userArr= [[NSMutableArray alloc] init];

}

//开始标签

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary  *)attributeDict{

NSLog(@"开始标签---- %@",elementName);

NSLog(@"attributeDict ------%@",attributeDict);

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

User *user = [[User alloc] init];

user.name= [attributeDict objectForKey:@"name"];

user.pwd= [attributeDict objectForKey:@"pwd"];

user.tureName= [attributeDict objectForKey:@"tureName"];

user.age= [attributeDict objectForKey:@"age"];

[_userArr addObject:user];

}

}

//请求数据和接收解析后的数据

- (void)viewDidLoad {

[super viewDidLoad];

NSURL* urL = [NSURL URLWithString:@"http://localhost:8080/Login1/NewServlet"];

NSMutableURLRequest * postRequest = [[NSMutableURLRequest alloc] initWithURL:urL];

[postRequest setHTTPMethod:@"POST"];

[postRequest setHTTPBody:[@"command=4" dataUsingEncoding:NSUTF8StringEncoding]];

[NSURLConnection sendAsynchronousRequest:postRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *_Nullableresponse,NSData *_Nullabledata,NSError *_NullableconnectionError) {

NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"data ---- %@",str);

FriendsClass * friend = [[FriendsClass alloc] initWithData:data];

for(User* user in friend.userArr) {

NSLog(@" ------ %@",user.name);

}

}];

}

你可能感兴趣的:(dom属性值解析)