Ios xml Parsing

Source: Internet
Author: User

The NSXMLParser of iOS SDK parses XML documents in the event-driven mode, that is, the XML Format documents are parsed In the SAX mode. When NSXMLParser encounters some elements (elements, attributes, CDATA blocks, comments, and so on) in the process of processing XML documents, it will notify the NSXMLParser of the Delegate, rather than processing the parsed elements, assign full authority to NSXMLParserDelegate for processing. It also reports errors.
1. Open an xml file and read the content to NSData.

NSString * path = [[NSBundle mainBundle] pathForResource: @ "filename" ofType: @ "xml"];
NSFileHandle * file = [NSFileHandle fileHandleForReadingAtPath: path];
NSData * data =;
;
2. Call initWithData of NSXMLParser: method and set the proxy delegate.


NSXMLParser * m_parser = [[NSXMLParser alloc] initWithData: data];
// Set this class as a proxy class, that is, the NSXMLParserDelegate delegation protocol must be implemented when the class is declared.
[M_parser setDelegate: self]; // sets the proxy to local.

BOOL flag = [m_parser parse]; // start Parsing
If (flag ){
NSLog (@ "succeeded in obtaining the xml file in the specified path ");
} Else {
NSLog (@ "failed to get the xml file in the specified path ");
}
[M_parser release];

Of course, there can be other initialization generation methods, such:

NSXMLParser * parser = [[NSXMLParser alloc] initWithContentsOfURL: [NSURL URLWithString: urlString];
You can directly customize a method to achieve resolution creation:


1-(void) parseXMLFileAtURL :( NSURL *) URL parseError :( NSError **) error {
2 NSXMLParser * parser = [[NSXMLParser alloc] initWithContentsOfURL: URL];
3 [parser setDelegate: self];
4 [parser setShouldProcessNamespaces: NO];
5 [parser setShouldReportNamespacePrefixes: NO];
6 [parser setShouldResolveExternalEntities: NO];
7 [parser parse];
8 NSError * parseError = [parser parserError];
9 if (parseError & error ){
10 * error = parseError;
11}
12 [parser release];
13}

 

3. Call the callback function.
When the preceding parser Initialization is complete and the parser statement is executed ([parser parse]), the program jumps to the proxy method and calls the callback function didStartElement. This method traverses the entire xml file, it also identifies the element name (elementName) in the xml, and creates an array or other variables to store the information when necessary. Generally, the storage operations are completed in the didEndElement callback function.

// Some initialization work can be done here before parsing
// Assume that the instance variables dataDict and parserObject have been declared.
-(Void) parserDidStartDocument :( NSXMLParser *) parser {
DataDict = [[NSMutableDictionary alloc] initWithCapacity: 0]; // each piece of information is stored in a dictionary.
ParserObjects = [[NSMutableArray alloc] init]; // each group of information is stored in an array. The final data obtained is in this array.
}

// This method is called when the parser object encounters the Start mark of xml.
// Get the nod Value
// Resolve to a start tag, which may contain properpies, for example, <book catalog = "programming">
// All attributes are stored in attributedict.
-(Void) parser :( nsxmlparser *) parser didstartelement :( nsstring *) elementname namespaceuri :( nsstring *) namespaceuri URI :( nsstring *) qualifiedname attributes :( nsdictionary *) attributedict {
If ([elementname isequaltostring: @ "book"]) {
Nsstring * catalog = [attributedict objectforkey: @ "catalog"];
} Else if (){
//......
}
}


// This method is called when the parser finds the character between the start mark and the end mark.
// Parser to read specific content from two nodes
-(Void) parser :( nsxmlparser *) parser foundcharacters :( nsstring *) string {
// Record the obtained text Column
} Www.2cto.com

-(Void) parser :( NSXMLParser *) parser foundCDATA :( NSData *) CDATABlock {
// NSLog (@ "cData: % @", [NSString stringwithuf8string: [CDATABlock bytes]);
}

// This method is called when the parser object encounters the xml end mark.
// Obtain the end value of the node. Here is the completion of the Tag.
-(Void) parser :( NSXMLParser *) parser didEndElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName {

}
// Some operations after xml parsing are available here
-(Void) parserDidEndDocument :( NSXMLParser *) parser {
//.....
}

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.