Parsing XML using Nsxmlparser in the IOS SDK (iphone Network chapter III)

Source: Internet
Author: User
Tags opening and closing tags

the IOS SDK's Nsxmlparser parsing XML document is an event-driven pattern that uses Sax to parse XML-formatted documents. Nsxmlparser notifies a delegate when it encounters some feature (element, attribute, cdata block, comment, and so on) while processing an XML document, and do not handle any of the elements of the parsing, and delegate to Nsxmlparserdelegate. It also reports errors.

1. Open an XML file and read the contents into the NSData.

NSString *path = [[NSBundle mainbundle] pathforresource:@ "filename" oftype:@ "xml"];
Nsfilehandle *file = [Nsfilehandle Filehandleforreadingatpath:path];
NSData *data = [File Readdatatoendoffile];
[File CloseFile];

2. Call Nsxmlparser's Initwithdata: Method and set the proxy delegate.

Nsxmlparser *m_parser = [[Nsxmlparser alloc] initwithdata:data];
Set the class itself as a proxy class, that is, the class implements the Nsxmlparserdelegate delegation protocol when declaring
[M_parser setdelegate:self]; Set Proxy to Local

BOOL flag = [M_parser parse]; Start parsing
if (flag) {
NSLog (@ "Get the XML file for the specified path succeeded");
}else{
NSLog (@ "Get XML file for specified path failed");
}
[M_parser release];

Of course, there are other ways to initialize the generator, such as:

Nsxmlparser *parser = [[Nsxmlparser alloc] Initwithcontentsofurl:[nsurl urlwithstring:urlstring]];

Directly customize a method to implement create parsing:

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) {
Ten *error = parseerror;
One }
[parser release];
13}

3. Call the callback function.
When the above parser is initialized and executes the parser statement ([parser parse]), the program jumps to the proxy method, invokes the callback function Didstartelement, which iterates through the entire XML, and identify the element name (elementname) inside the XML, creating an array or other variable to store the information at the appropriate time when discovering the information to find. In general, the operation to complete the related storage is often done in the didendelement callback function.

Before you start parsing, you can do some initialization work here
Suppose you have declared an instance variable Datadict,parserobject
-(void) Parserdidstartdocument: (Nsxmlparser *) Parser {
Datadict = [[Nsmutabledictionary alloc] initwithcapacity:0]; Every piece of information is stored in a dictionary.
Parserobjects = [[Nsmutablearray alloc] init]; Each set of information is stored in an array, and the resulting data is in this array
}
This method is called when the parser object encounters the start tag of the XML.
Get the value of nodding
Parse to a start tag, there may be properpies in the tag, such as <book catalog= "Programming" >
All properties are stored in attributedict
-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (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 opening and closing tags.
Parser to read specific content from two nodes
-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string {
Record the obtained text column
}

-(void) Parser: (Nsxmlparser *) parser Foundcdata: (NSData *) cdatablock{

}
This method is called when the parser object encounters the end tag of the XML.
Gets the value at the end of the junction, where a tag is completed
-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) QName {

}
Some actions after the end of XML parsing can be
-(void) Parserdidenddocument: (Nsxmlparser *) Parser {
//.....
}


About Me Learning Nsxmlpareser parsing XML once produced problems and troubleshoot:

    • Like the following XML document structure, the analysis is read from imglist, not the IMG table node. Otherwise it will be read only once and will not be looped.
      <src> picture address 1</src><name> picture name 1</name><url> picture Specify a hyperlink 1</ Url></img>
      <src> picture address 2</src><name> picture name 2</name><url> picture Specify a hyperlink 2</url></img ></imgList>
    • The basic idea of organizing related entity class definitions from the XML document structure is to define each new node container as a new entity class.

Parsing XML using Nsxmlparser in the IOS SDK (iphone Network chapter III)

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.