IOS explanation nsxmlparser method XML data parsing method

Source: Internet
Author: User

The previous article introduced how to obtain XML data from the network through URLs. The following describes how to parse the obtained data.

Let's take a look at the XML data format!

<?xml version="1.0" encoding="UTF-8"?><Books><Book id="1"><title>Circumference</title><author>Nicholas Nicastro</author><summary>Eratosthenes and the Ancient</summary></Book><Book id="2"><title>Copernicus Secret</title><author>Jack Repcheck</author><summary>How the scientific revolution began</summary></Book><Book id="3"><title>Angels and Demons</title><author>Dan Brown</author><summary>Robert Langdon is summoned to a Swiss</summary></Book></Books>

Obviously, this XML contains some basic data of the three books: The process of parsing the ID Title Author summary is to extract the data.

Let's briefly introduce XML data parsing. XML data can be parsed in two ways:SAX (Simple API for XML) and Dom (Document Object Model), Events and documents.

The principle of Dom implementation is to read the entire XML document at one time and put it in a tree structure. When necessary, find a specific node and then read or write the node. Its main advantage is its simplicity and read/write balance. Its disadvantage is that it occupies the memory because it reads the entire XML file into the memory. The larger the file, the more obvious this disadvantage is.

The implementation method of Sax is different from that of Dom. He only searches for the content of a specific condition in the XML document and extracts only the required content. In this way, the memory usage is small and flexible.

Nsxmlparser implements the sax method to parse XML files.

The following topic describes how to parse XML:

1. Save the preceding XML data as books. XML as the local XML data and import it to the project.

Ii. Because the book contains several attributes, the first book class here.

Book. h file:

#import <Foundation/Foundation.h>@interface Book : NSObject@property (nonatomic, readwrite) NSInteger bookID;@property (nonatomic, retain) NSString  *title;@property (nonatomic, retain) NSString  *author;@property (nonatomic, retain) NSString  *summary;@end

Book. M file

#import "Book.h"@implementation Book@synthesize bookID;@synthesize title;@synthesize author;@synthesize summary;@end

3. parse XML data by implementing several methods in the nsxmlparserdelegate delegate.

# Pragma mark xmlparser // Step 1: Prepare for parsing-(void) parserdidstartdocument :( nsxmlparser *) parser {} // Step 2: Prepare the parsing node-(void) parser :( nsxmlparser *) parser didstartelement :( nsstring *) elementname namespaceuri :( nsstring *) namespaceuri qualifiedname :( nsstring *) QNAME attributes :( nsdictionary *) attributedict {} // Step 3: get content between the beginning and end nodes-(void) parser :( nsxmlparser *) parser foundcharacters :( nsstring *) string {}// Step 4: parse the current node-(void) parser :( nsxmlparser *) parser didendelement :( nsstring *) elementname namespaceuri :( nsstring *) namespaceuri qualifiedname :( nsstring *) QNAME {} // Step 5: resolution end-(void) parserdidenddocument :( nsxmlparser *) parser {} // Step 6: Obtain CDATA block data-(void) parser :( nsxmlparser *) parser foundcdata :( nsdata *) cdatablock {}

Step 3, 4, and 5 in the above method are required in the XML parsing process, and step 1 and 5 are optional.

The following sections describe:

Step 1: Some preparations before starting parsing, such as initializing some storage variables. In my example, a book instance variable is used to store a book (that is, a set of information ), A variable array is used to store the three books (that is, each group of information is regarded as an element in the array). (this time, you must understand the relationship between data variables ), other variables will not be introduced for the moment (you can view the source code later ).

Step 2: When the parser encounters the XML root tag and the start tag of a group of information, it starts to call this method. In this XML file, it encounters the books (root tag of the XML file ), this method is called when book (the start label of a set of information. Then we can know that this method has been called many times during the program running. Then you can use the if statement to determine whether to encounter books or books, and then perform some corresponding operations (For details, refer to the source code ).

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

Note that the parameter elementname indicates the tag encountered. In this program, books and book are encountered. When a tag is parsed, the initial tag may have some attributes, for example, <book id = "1">

Then, ID is the attribute. In this method, it is stored in a dictionary (nsdictionary *) attributedict, then you can obtain the value and key for this dictionary operation.

Step 3: When the parser finds the character between the start tag and the end tag, it calls this method to read the content. Note: The string read here is not included in this function. It means that if the string content is circumference (book title ), but we don't know where this is the title content; so we can only know where it is, and then store it. Don't worry, that is, step 4!

Step 4: This method is called when the parser reads the end tag. For example, reading books, book, and title. Then you can store the read tags after judging them!

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName  {     } 

Here, the label parameter is elementname.

Step 5: perform operations after the XML file is parsed.

Step 6: This is not explained yet (I have not used it yet ).

4. The following is the time for the code.

. H file

# Import <uikit/uikit. h> @ Class appdelegate, book; @ interface viewcontroller: uiviewcontroller <nsxmlparserdelegate> {nsmutablestring * currentelementvalue; // nsmutablearray * books is used to store the value of element labels; // stores a set of books * shortk; // a book instance that represents a book bool storingflag; // queries whether the elements corresponding to a tag have nsarray * elementtoparse; // elements to be stored}-(ibaction) xmlbutton :( ID) sender; @ end

Note: Here I use a button to trigger XML parsing.

. M file

# Import "viewcontroller. H "# import" appdelegate. H "@ interface viewcontroller () @ end @ implementation viewcontroller-(void) viewdidload {[Super viewdidload]; // do any additional setup after loading the view, typically from a nib. // initialize the element tag elementtoparse = [[nsarray alloc] initwithobjects: @ "title", @ "author", @ "summary", nil];}-(void) didreceivememorywarning {[Super didreceivememorywarning]; // dispos E of any resources that can be recreated .} -(void) parser :( nsxmlparser *) parser didstartelement :( nsstring *) elementname namespaceuri :( nsstring *) namespaceuri qualifiedname :( nsstring *) QNAME attributes :( nsdictionary *) attributedict {If ([elementname isinclutostring: @ "books"]) {// initialize the array. // initialize the array variable used to store the final parsing result here. We started to initialize books = [[nsmutablearray alloc] init] when encountering the books root element;} else if ([E Lementname isequaltostring: @ "book"]) {// initialize the book. // when a book element is encountered, the instance object used to store book information is initialized. Optional K keys K = [[Book alloc] init]; // extract the attribute here. // read the attribute aBook of the book element from the attributedict dictionary. bookid = [[attributedict objectforkey: @ "ID"] integervalue]; nslog (@ "ID: % I", aBook. bookid);} storingflag = [elementtoparse containsobject: elementname]; // determine whether the object to be stored exists}-(void) parser :( nsxmlparser *) parser Foundcharacters :( nsstring *) string {// when the value used to store the current element is null, the value is first initialized and assigned. // otherwise, the information is directly appended if (storingflag) {If (! Currentelementvalue) {currentelementvalue = [[nsmutablestring alloc] initwithstring: String];} else {[currentelementvalue appendstring: String] ;}} // here is where the final result of the entire parsing and data storage is actually completed-(void) parser :( nsxmlparser *) parser didendelement :( nsstring *) elementname namespaceuri :( nsstring *) namespaceuri qualifiedname :( nsstring *) QNAME {If ([elementname is1_tostring: @ "book"]) {[books addobject: Empty K]; shard K = nil;} If (storingflag) {// remove the space nsstring * trimmedstring = [currentelementvalue character: [nscharacterset whitespaceandnewlinecharacterset]; // empty the string [currentelementvalue setstring: @ ""]; if ([elementname isequaltostring: @ "title"]) {comment K. title = trimmedstring; nslog (@ "title: % @", comment K. title);} If ([elementname isinclutostring: @ "author"]) {comment K. author = trimmedstring; nslog (@ "Author: % @", aBook. author);} If ([elementname isinclutostring: @ "summary"]) {polick. summary = trimmedstring; nslog (@ "Summary: % @", using K. summary) ;}}- (ibaction) xmlbutton :( ID) sender {// open the XML file and read data to nsdata nsstring * Path = [[nsbundle mainbundle] pathforresource: @ "books" oftype: @ "XML"]; nsfilehandle * file = [nsfilehandle filehandleforreadingatpath: path]; nsdata * Data = ;; // test the data received from XML nsstring * datastring = [[nsstring alloc] initwithdata: data encoding: nsutf8stringencoding]; nslog (@ "% @", datastring ); nsxmlparser * m_parser = [[nsxmlparser alloc] initwithdata: Data]; // sets this class as a proxy class, that is, the class must implement the nsxmlparserdelegate delegate Protocol [m_parser setdelegate: Self] During Declaration; // set the proxy to local bool flag = [m_parser parse]; // start parsing if (FLAG) {nslog (@ "parsing the XML file in the specified path succeeded ");} else {nslog (@ "failed to parse the XML file in the specified path"); }}@ end

Note:

1. I used some nslogs to output the relevant information for verification. In actual use, it would be okay to remove them!

2. In combination with the above explanation and code, we should be able to understand the entire XML parsing process.

3. Here I use a local XML file. If I want to parse the XML data of the network, it is also very simple, the local XML here is replaced by the XML data obtained through the URL. For more information about how to obtain XML from the URL, see the previous blog.

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.