IOS IM development preparation (I) XML parsing, iosim

Source: Internet
Author: User

IOS IM development preparation (I) XML parsing, iosim

There are many blogs about XML parsing that I didn't want to write, but I found that they didn't talk about any details. I will talk about some details here.

Where can we use XML? Currently, there is not much json communication. In my scenario, there are many servers that need to be selected by users. We need to maintain a server list on a regular basis. The configuration file of this server list needs to be downloaded each time. Naturally, I need to parse this file.

XML parsing has two modes: SAX and DOM. I am using the NSXMLParser of the system. It is a SAX parsing.

I wrote a tool class, first paste the code, the following will have some instructions

. H

1 # import <Foundation/Foundation. h> 2 3 typedef NS_ENUM (NSInteger, xmlModelName) {// here I made a difference to my XML file because I want to parse two types of expressions: 4 xmlModelNameFace, 5 xmlModelNameServer and server list, 6}; 7 @ interface XMLParser: NSObject <NSXMLParserDelegate> 8 // This is the callback Block 9 @ property (nonatomic, copy) void (^ returnParseArray) (NSArray * returnArray ); 10 @ property (nonatomic, readonly) xmlModelName currentModelName; 11 12-(instancetype) initWithFilePath :( NSString *) path fileType :( NSString *) fileType modelName :( xmlModelName) modelName; 13 14-(void) startWithFilePath :( NSString *) path fileType :( NSString *) fileType; 15 @ end

. M

1 # import "XMLParser. h "2 # import" FaceModel. h "3 # import" ToolClient. h "4 # import" ServerModel. h "5 @ implementation XMLParser {6 NSMutableArray * faceArray; 7 NSMutableArray * serverArray; 8} 9 10 @ synthesize currentModelName; 11-(instancetype) initWithFilePath :( NSString *) path fileType :( NSString *) fileType modelName :( xmlModelName) modelName {12 self = [super init]; 13 if (self) {14 currentModelName = modelName; 15} 16 return self; 17} 18 19-(void) startWithFilePath :( NSString *) path fileType :( NSString *) fileType {20 [self parseWithPath: path type: fileType]; 21} 22 // 23-(void) parseWithPath :( NSString *) filePath type :( NSString *) fileType {24 if (currentModelName = xmlModelNameFace) {25 faceArray = [[NSMutableArray alloc] init]; 26} else if (currentModelName = xmlModelNameServer) {27 serverArray = [[NSMutableArray alloc] init]; 28} 29 NSData * xmlData = [[NSData alloc] initWithContentsOfFile: filePath]; 30 if (xmlData & xmlData. length> 10) {31 NSXMLParser * parser = [[NSXMLParser alloc] initWithData: xmlData]; 32 [parser setShouldProcessNamespaces: NO]; 33 [parser setShouldReportNamespacePrefixes: NO]; 34 [parser setShouldResolveExternalEntities: NO]; 35 [parser setDelegate: self]; 36 BOOL success = [parser parse]; 37 if (success) {38 [self parseSuccess]; 39} else {40 [ToolClient activityShowMessage: @ "XML parsing failed" inView: [UIApplication sharedApplication]. windows [0]; 41} 42} else {43 [ToolClient activityShowMessage: @ "XML parsing failed" inView: [UIApplication sharedApplication]. windows [0]; 44} 45} 46 // callback after successful 47-(void) parseSuccess {48 if (self. returnParseArray) {49 if (currentModelName = xmlModelNameFace) {50 self. returnParseArray (faceArray); 51} else if (currentModelName = xmlModelNameServer) {52 self. returnParseArray (serverArray); 53} 54} 55} 56 # pragma mark-prop 58-(void) parser :( NSXMLParser *) parser didStartElement :( NSString *) elementName59 namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qualifiedName60 attributes :( NSDictionary *) attributeDict {61 // NSLog (@ "Name: % @", elementName); 62 63 if ([elementName isinclutostring: @ "face"] & currentModelName = xmlModelNameFace) {64 FaceModel * faceModel = [[FaceModel alloc] init]; 65 faceModel. kID = [attributeDict [@ "id"] intValue]; 66 faceModel. kName = attributeDict [@ "name"]; 67 faceModel. kImage = attributeDict [@ "file"]; 68 [faceArray addObject: faceModel]; 69 faceModel = nil; 70} else if ([elementName isEqualToString: @ "Server"] & currentModelName = xmlModelNameServer) {71 ServerModel * sModel = [[ServerModel alloc] init]; 72 sModel. serverName = attributeDict [@ "name"]; 73 sModel. serverIP = attributeDict [@ "ChatServerIP"]; 74 sModel. chatPort = attributeDict [@ "chatPort"]; 75 sModel. fileServerIP = attributeDict [@ "fileServerIP"]; 76 sModel. filePort = attributeDict [@ "filePort"]; 77 [serverArray addObject: sModel]; 78 sModel = nil; 79} 80} 81-(void) parser :( NSXMLParser *) parser foundCharacters :( NSString *) string {82 // NSLog (@ "value: % @", string); 83} 84-(void) parserDidEndDocument :( NSXMLParser *) parser {85 // 86 // NSLog (@ "% @", faceArray); 87 88} 89-(void) parser :( NSXMLParser *) parser didEndElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName {90 // NSLog (@ "elementName: % @", elementName); 91 // NSLog (@ "qualifiedName: % @ ", qName); 92 // 93 // NSLog (@" NSXMLParserDone "); 94 // NSLog (@" % @ ", faceArray ); 95 // NSLog (@ "% I", (int) faceArray. count); 96 97} 98 @ end

Now let me talk about the role of the three NO parameters in XML parsing settings.

1 [parser setShouldProcessNamespaces: NO]; 2 [parser setShouldReportNamespacePrefixes: NO]; 3 [parser setShouldResolveExternalEntities: NO];

If the first setShouldProcessNamespaces attribute is set to YES, the two methods will have value output:parser:didStartElement:namespaceURI:qualifiedName:attributes:AndParser: didEndElement: namespaceURI: qualifiedName: both of them can see the node or field name in the parsing process. I think it can be used during debugging.

If the second setShouldReportNamespacePrefixes attribute is set to YES, the two methods will have a value output:parser:didStartMappingPrefix:toURI:AndParser: didEndMappingPrefix: I don't think it is necessary to use it.

If the setShouldResolveExternalEntities attribute is set to YES, this method will output a value: parser: foundExternalEntityDeclarationWithName: publicID: systemID: Where publicID and systemID are unique identifiers of the XML document. This is what the official documentation says about these two variables:

You may access this property once a parsing operation has begun or after an error occurs.

That is, when XML parsing has started or an error occurs, you can check it again. That is to say, if your XML is good enough, you can ignore it.

The above code is a tool class. The following section will show you how to use this code:

1 // parse file 2-(void) parseFile :( NSString *) filepath {3 NSLog (@ "filepath % @", filepath); // File Path 4 if (data. length> 10) {// simple length Detection 5__ weak SelectServerViewController * ws = self; // weak reference 6 // do parse 7 XMLParser * xp = [[XMLParser alloc] initWithFilePath: filepath fileType: @ "xml" modelName: xmlModelNameServer]; 8 // configure callback 9 xp first. returnParseArray = ^ (NSArray * array) {10 // The callback result is displayed to tableView 11 [ws gotDataArray: array]; 12 }; 13 // start parsing 14 [xp startWithFilePath: filepath fileType: @ "xml"]; 15} 16 17} 18 19-(void) gotDataArray :( NSArray *) array {20 if (array) {21 // NSLog (@ "array: % @", array); 22 dataArray = [array mutableCopy]; 23 [myTableView reloadData]; 24} 25}

I have written so much about XML parsing. I suggest using a Model to store data during parsing, which will be very convenient for later use.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.