标签:
一、利用xmpp里的扩展文件进行xml数据解析,xml数据解析的框架需要自己手动写出。
包含这个头文件NSXMLElement+XMPP.m。主要使用了这个文件中的如下方法:
- (NSXMLElement *)elementForName:(NSString *)name { NSArray *elements = [self elementsForName:name]; if ([elements count] > 0) { return [elements objectAtIndex:0]; } else { // There is a bug in the NSXMLElement elementsForName: method. // Consider the following XML fragment: // // <query xmlns="jabber:iq:private"> // <x xmlns="some:other:namespace"></x> // </query> // // Calling [query elementsForName:@"x"] results in an empty array! // // However, it will work properly if you use the following: // [query elementsForLocalName:@"x" URI:@"some:other:namespace"] // // The trouble with this is that we may not always know the xmlns in advance, // so in this particular case there is no way to access the element without looping through the children. // // This bug was submitted to apple on June 1st, 2007 and was classified as "serious". // // --!!-- This bug does NOT exist in DDXML --!!-- return nil; } }
xml数据解析框架书写,针对不同的xml数据节点书写不同,可以抽出为一个通用性更广泛的方法。
- (NSArray *)emailAddresses { //获取Email节点 NSXMLElement *emailEle = [self elementForName:@"EMAIL"]; //获取Email的子节点 // NSArray *children = [emailEle children]; // WCLog(@"%@",children); NSXMLElement *useridEle = [emailEle elementForName:@"USERID"]; //获取邮箱 NSString *email = [useridEle stringValue]; WCLog(@"%@",email); #warning 只返加USERID的邮箱 if (email.length > 0) { return @[email]; } return nil; }
//获取邮箱 NSArray *emails = myvCard.emailAddresses; if (emails.count > 0) { self.emailLabel.text = emails[0];; }
二、利用xmpp里的扩展文件进行xml数据添加、删除、更改,xml数据添加的框架需要自己手动写出。
包含这个头文件NSXMLElement+XMPP.m。主要使用了这个文件中的如下方法对节点进行删除:
/** * This method removes the first child element for the given name. * If no child elements exist for the given name, this method does nothing. **/ - (void)removeElementForName:(NSString *)name { NSXMLElement *element = [self elementForName:name]; if(element) { [self removeChildAtIndex:[[self children] indexOfObject:element]]; } }
包含这个头文件DDXMLNode.m。主要使用了这个文件中的如下方法设置新的节点:
+ (id)elementWithName:(NSString *)name stringValue:(NSString *)string { return [[DDXMLElement alloc] initWithName:name stringValue:string]; }
- (void)setEmailAddresses:(NSArray *)emails { //邮箱数组只能有一个邮箱 NSAssert(emails.count == 1,@"邮箱数组只能有一个邮箱"); /* * <EMAIL> <HOME /> <INTERNET /> <PREF /> <USERID>lisi@itcast.cn</USERID> </EMAIL> */ //获取Email节点 NSXMLElement *emailEle = [self elementForName:@"EMAIL"]; // //获取Email下的USERID的子节点 // NSXMLElement *useridEle = [emailEle elementForName:@"USERID"]; // //更新USERID的内容 //删除USERID节点 [emailEle removeElementForName:@"USERID"]; //添加回节点 NSXMLElement *useridEle = [NSXMLElement elementWithName:@"USERID" stringValue:emails[0]]; //把USERID添加到email节点下 [emailEle addChild:useridEle]; }
//解析邮箱 //myVCard.mailer = self.emailLabel.text; if (self.emailLabel.text.length > 0) { // 只保存一个邮箱 myVCard.emailAddresses = @[self.emailLabel.text]; }
标签:
原文地址:http://blog.csdn.net/gongwutianya/article/details/51336012