IOS development practices-XML

Source: Internet
Author: User

IOS development practices-XML

For the comparison between xml and json, we have provided a reference in the previous article. The syntax structure of xml is not described here. Go straight to the xml Parsing Method in iOS.

XML parsing (Dom and SAX) in iOS)

The Dom method uses the Document Object Model parsing. It first reads the xml file into the memory, and then constructs the Dom object. In the DOM object, all elements in the xml file can be processed as Node objects. This method facilitates the addition, deletion, modification, and addition of documents. The disadvantage is that it must first read the entire file into the memory for parsing, if the file is large. Memory is consumed, and the execution speed is slow.

An event-driven method is used to parse XML files. That is to say, a file is scanned row-by-row. When a specified condition is met, a specific event is triggered, call back the event handler you have written. The advantage of using SAX lies in its fast resolution speed and low memory usage (relative to DOM ). In addition, you can terminate the parsing at any time after obtaining the information you need during File Parsing. It is not necessary to wait until all the File Parsing is complete. There are advantages and disadvantages in everything. The disadvantage is that SAX uses stream processing. When a tag is encountered, it does not record the previously encountered tag. That is to say, when processing a tag, the information obtained is the Tag Name and attribute. As for the nested structure inside the tag, information related to its structure, such as the upper-layer label, lower-layer label, and the name of its brother node, is unknown. In fact, the structure information of the XML file is lost. If you need this information, you can only process it yourself in the program. Therefore, compared with DOM, it is not convenient for SAX to process XML documents, and the process of SAX processing is more complex than DOM.

Summary:

DOM: loads the entire XML file into the memory at a time, which is suitable for parsing small files.

SAX: event-driven. It is suitable for parsing large files from the root element to one element in sequence.

Resolution method:

Apple native

NSXMLParser: simple to use

Third-party framework

Libxml2: pure C language. It is included in the iOS SDK by default and supports DOM and SAX parsing.

GDataXML: DOM-based parsing, developed by Google, based on libxml2

XML parsing method selection suggestions

Large files: NSXMLParser and libxml2

Small file: GDataXML

GDataXML:

Common classes

GDataXMLDocument: represents the entire XML document

GDataXMLElement: represents each element in the document

Common Methods:

ElementsForName: obtains the Element Node Based on the element name.

AttributeForName: The method can obtain the attribute value.

For more xml methods and attributes, refer to GDataXMLNode. h.

Procedure:

1. Download GDataXMLNode: http://download.csdn.net/detail/zhixin#com/9425644 and decompress the GDataXMLNode. h and GDataXMLNode. m files to the project.

2. Because GDataXML is based on the libxml2 library, you need to import libxml2

3. Set the header file search path of libxml2 (in order to find all header files of libxml2 library)

InHead Search PathAdd/usr/include/libxml2


 

4. Set link parameters (automatically linking libxml2 library)

InOther Linker Flags-Lxml2

 

5. If an arc error is reported, set the GDataXML compilation parameter.

 

6. import the # import "GDataXMLNode. h" header file.

Example:

Parse xml in the following format

-(Void) touchesBegan :( NSSet
 
  
*) Touches withEvent :( UIEvent *) event {NSURL * url = [NSURL URLWithString: @ "http: // localhost: 8080/myService/video? Type = XML "]; NSURLRequest * request = [NSURLRequest requestWithURL: url]; [NSURLConnection failed: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * _ Nullable response, NSData * _ Nullable data, NSError * _ Nullable connectionError) {// 1. load xml data GDataXMLDocument * document = [[GDataXMLDocument alloc] initWithData: data options: 0 error: nil]; // 2. Get the xml root element (videos) GDataXMLElement * root = document. rootElement; // Number of element subnodes (excluding nodes under the subnode) // NSInteger childCount = root. childCount; // element name // NSString * elementName = root. name; // node content string // NSString * xmlStr = root. XMLString; // NSLog (@ "childCount = % ld \ nelementName = % @ \ nxmlStr = % @", childCount, elementName, xmlStr ); // 3. obtain all the video elements of the root element NSArray * elements = [root elementsForName: @ "video"]; for (GDataXMLElement * element in elements) {// 4. Obtain the attribute NSString * idStr = [element attributeForName: @ "id"]. stringValue; NSString * name = [element attributeForName: @ "name"]. stringValue; NSString * length = [element attributeForName: @ "length"]. stringValue; NSString * image = [element attributeForName: @ "image"]. stringValue; NSString * url = [element attributeForName: @ "url"]. stringValue; NSLog (@ "id = % @", idStr); NSLog (@ "name = % @", name); NSLog (@ "length = % @", length); NSLog (@ "image = % @", image); NSLog (@ "url = % @", url) ;}}];}
 

NSXMLParser:

NSXMLParser adopts the SAX parsing method, which is event-driven. The proxy will be notified in the following cases:

(1) when the Document is scanned

(2) When the Element is scanned

1. steps:

1. Input XML data and create a parser

NSXMLParser * parser = [[NSXMLParseralloc] initWithData: data];

2. Set the proxy and listen to the parsing process

Parser. delegate = self;

3. Start Parsing

[Parserparse];

Ii. Common NSXMLParserDelegate proxy methods:

Call (start parsing) when scanning the beginning of a document)

-(Void) parserDidStartDocument :( NSXMLParser *) parser

Called upon scanning to the end of the document (resolution completed)

-(Void) parserDidEndDocument :( NSXMLParser *) parser

It is called when an element is scanned to start (attributeDict stores the attribute of the element)

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

Called at the end of an element Scan

-(Void) parser :( NSXMLParser *) parser didEndElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName


Example: parse the xml format above
# Import "ViewController. h" @ interface ViewController ()
 
  
@ End @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.}-(void) touchesBegan :( NSSet
  
   
*) Touches withEvent :( UIEvent *) event {NSURL * url = [NSURL URLWithString: @ "http: // localhost: 8080/myService/video? Type = XML "]; NSURLRequest * request = [NSURLRequest requestWithURL: url]; [NSURLConnection failed: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * _ Nullable response, NSData * _ Nullable data, NSError * _ Nullable connectionError) {// 1. Input xml and create the parser NSXMLParser * parser = [[NSXMLParser alloc] initWithData: data]; // 2. Set proxy and listen to parser during parsing. delegate = self; // 3. Start parsing [parser parse];} # pragma mark NSXMLParserDelegate proxy method // this method is called when an element is scanned to start (attributeDict stores the attribute of the element)-(void) parser :( NSXMLParser *) parser didStartElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName attributes :( NSDictionary
   
    
*) AttributeDict {NSLog (@ "==============%@ element start parsing =========", elementName ); if ([@ "videos" isEqualToString: elementName]) {NSLog (@ "% @ is the root node", elementName); return ;} NSString * idStr = attributeDict [@ "id"]; NSString * name = attributeDict [@ "name"]; NSString * length = attributeDict [@ "length"]; NSString * image = attributeDict [@ "image"]; NSString * urlStr = attributeDict [@ "url"]; NSLog (@ "\ n id = % @ \ n name = % @ \ n length = % @ \ n image = % @ \ n url = % @", idStr, name, length, image, urlStr) ;}; // call-(void) parser :( NSXMLParser *) parser didEndElement :( NSString *) elementName namespaceURI :( NSString *) When the element is scanned *) namespaceURI qualifiedName :( NSString *) qName {NSLog (@ "============%@ end of element resolution ====== ", elementName);} // call (start parsing)-(void) parserDidStartDocument :( NSXMLParser *) when the document is scanned *) parser {NSLog (@ "parserDidStartDocument ==== start parsing ======") ;}// call it when the scanning ends at the end of the document (resolution is complete) -(void) parserDidEndDocument :( NSXMLParser *) parser {NSLog (@ "parserDidEndDocument ==== resolution complete ======");} @ end
   
  
 
Parse the input result:

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.