XML file parsing-XML-files nsxmlparser

Source: Internet
Author: User

From: http://hi.baidu.com/hh20040410/blog/item/90c32d18ce26d6bd4bedbc25.html/cmtid/da6d7ba2d518bea1caefd0b0

XML File Parsing Method

XML is used to increase the Web Data Exchange volume. Although it is not widely used in Web applications, it is often used as a configuration file because of its good format. For example, Tomcat's main configuration file server. XML and Web. xml. First, let's take a look at the requirements. Our goal is to extract specific content from an XML file. Because the XML file is in good format, this query is very regular and is very helpful for us to find the required information. Sometimes we may write specific information back to XML, but this requirement is not necessary, because the configuration files are not too large, and we can modify it manually. There are two standards for XML parsing: Sax and Dom. First, these two standards are not for Java, and they can be implemented in various language environments. Dom is a real international standard. Sax is the standard of fact. It is operated by a non-commercial organization rather than maintenance by any commercial organization. Just like the iso7 Layer Model and TCP/IP, although Sax is not a formal standard, it does not affect its position in the XML parsing field. 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, meeting our needs. His disadvantage is writing. Some documents introduce the writing method, but I don't think this is necessary for this example.

Nsxmlparser implements the sax method to parse XML files.
References:
Http://www.iphonesdkarticles.com/2008/11/parsing-xml-files.html (reference 1)

[Reference 2] http://codesofa.com/blog/archive/2008/07/23/make-nsxmlparser-your-friend.html

Introduction

NsxmlparserIs a forward only reader or an event driven parser. what it means is, an event is raised whenever the parser comes when SS a start of an element, value, CDATA and so on. the delegate of nsxmlparser can then implement these events to capture XML data. some of the events are raised multiple times like the start of an element, value of an element and so on. since nsxmlparser is known as an event driven parser, we can only read data at the present node and cannot go back. the iPhone only supports nsxmlparser and not nsxmldocument, which loads the whole XML tree in memory.

For example, say you have a simple XML file such as the following:

<? XML version = "1.0" encoding = "utf8">
<Article author = "John Doe">
<Para> This is a very short article. </para>
</Article>

The parser wocould report the following series of events to its delegate:

  1. Started parsing document

  2. Found start tag for elementArticle--- <Article>

  3. Found attributeAuthorOf ElementArticle, Value "John Doe" ----- author = "John Doe"

  4. Found start tag for elementPara -----<Para>

  5. Found characters ------This is a very short article .【Element's Value]

  6. FoundEnd tagForElement Para------</Para>

  7. FoundEnd tagForElement Article ----</Article>

  8. Ended parsing document

 

UseNsxmlparserProcedureAs follows:



Step 1To determine how to save the data parsed from the XML file-define a class (struct)

TIPS: The data parsed by an XML file may contain multiple objects.Nsmutablearray to save. See books mentioned in section 1.

Step 2,Custom resolution processing method (Three methods)--DelegateProxy

To enableCodeClear can be proposed separately as a class

Method 1:

-(Void) parser :( nsxmlparser *) parser didstartelement :( nsstring *) elementname
Namespaceuri :( nsstring *) namespaceuri qualifiedname :( nsstring *) qualifiedname
Attributes :( nsdictionary *) attributedict {

/*

* ProcessingI. Start tag for element creates different objects (struct) for saving corresponding data information based on different element names)

* Process 2:Attribute of the element stores data information to an object (struct)

*/

If ([ElementnameIsequaltostring: @ "books"]) {
// Initialize the array.
Appdelegate. Books = [[nsmutablearray alloc] init];
}

Required K. bookid = [[AttributedictObjectforkey: @ "ID"] integervalue];

}

Method 2:Main ProcessingElement's ValueGenerally, they are stored as follows:Value to string

-(Void) parser :( nsxmlparser *) parser foundcharacters :( nsstring *) string {

If (! Currentelementvalue)
Currentelementvalue = [[nsmutablestring alloc] initwithstring: String];
Else
[Currentelementvalue appendstring: String];

Nslog (@ "processing value: % @", currentelementvalue );

}

Method 3:

-(Void) parser :( nsxmlparser *) parser didendelement :( nsstring *) elementname
Namespaceuri :( nsstring *) namespaceuri qualifiedname :( nsstring *) QNAME {

/*

* ProcessingEnd tagElement to determine the names of different elements and save them with different processing methods.

*/

If ([ElementnameIsequaltostring: @ "book"]) {
[Appdelegate. Books addobject: Permission K];

[ABook release];
Required K = nil;
}

}

Step 3Get the XML file and createNsxmlparser object, afterAnalysis

For example, refer to instance 1 to obtain the XML file from the URL and instantiate it.Nsxmlparser object

Nsurl * url = [[nsurl alloc] initwithstring: @ "http://sites.google.com/site/iphonesdktutorials/xml/Books.xml"];
Nsxmlparser * xmlparser = [[nsxmlparser alloc]Initwithcontentsofurl: Url];

// Initialize the delegate. instantiate the proxy of the resolution processing method (the proxy defined in step 2)
Xmlparser * parser = [[xmlparser alloc] initxmlparser];

// Set delegate settingsNsxmlparser Object Parsing Method proxy
[XmlparserSetdelegate: Parser];

// Start parsing the XML file. Call proxy resolutionNsxmlparser object
Bool success = [xmlparser parse];

If (SUCCESS)
Nslog (@ "no errors ");
Else
Nslog (@ "Error error !!! ");


/*********************

* That all

/*********************

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.