"Self-describing" structured documents
1 XML Document Structure
Declaration: Defines the version of the XML file and the character set used <>
Root element: start tag end tag
Child element: start tag end tag
Properties: Defines the property name attribute value in the start tag (placed between double or single quotes) an element cannot have more than one property with the same name.
Namespaces: Provide unique elements and attributes for the XML document
************
The XML namespace provides a way to avoid element naming conflicts.
XML Namespace (xmlns) attribute
The XML namespace attribute is placed in the start tag of the element and uses the following syntax:
xmlns:namespace-prefix= "NamespaceURI"
When a namespace is defined in the start tag of an element, all child elements with the same prefix are associated with the same namespace.
Note: The address used to mark the namespace is not used by the parser to find information. Its only function is to give the namespace a unique name. However, many companies often use namespaces as pointers to the actual web pages that contain information about namespaces.
**************
Qualified Name: A legal identifier that defines the element and attribute, used as a reference to a particular element or attribute
2 parsing the use of XML documents Nsxml
The default parsing framework, which uses event-driven Sax mode parsing, encounters tags and attributes that trigger corresponding events that can only be read and cannot be modified.
The core is Nsxmlparser and nsxmlparserdelegate.
Method: Parserdidstartdocument: Triggers when the document starts
Parser:didStartElement:namespaceURI:qualifiedName:attributes: Triggered when a start tag is encountered
Parser:foundcharacters: Trigger trigger character when string is encountered including line feed and carriage return
Parser:didEndElement:namespaceURI:qulifiedName: Triggered when an end tag is encountered
Parserdisenddocument: The end of the document triggers parsing to complete cleanup variable return data to presentation layer
Parser Class Code:
Nsxmlparser is the parse class constructor-initwithcontentofurl:-initwithdata:-initwithstream:
-(void) start{NSString* Path = [[NSBundle mainbundle] Pathforresource:@"Notes"OfType:@"XML"]; Nsurl *url = [Nsurl Fileurlwithpath:path]; the other is urlwithstring://Start parsing XML Nsxmlparser *parser = [[Nsxmlparser alloc] initwithcontentsofurl:url]; Parser.Delegate=Self ; [Parser parse]; NSLog (@"Parse Complete ...");}//triggers when the document starts- (void) Parserdidstartdocument: (Nsxmlparser *) parser{_notes= [NsmutablearrayNew]; Initialize, in order to load parsed data }//trigger when the document is in error- (void) Parser: (Nsxmlparser *) parser parseerroroccurred: (Nserror *) parseerror{NSLog (@"%@", parseerror);}//triggered when a start tag is encountered- (void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString*) NamespaceURI qualifiedname: (NSString*) QualifiedName attributes: (nsdictionary*) attributedict Property dictionary { _currenttagname = elementname; marks the location of the current parserif([_currenttagname isequaltostring:@"Note"]) {nsstring*_id = [Attributedict objectforkey:@"ID"]; value is 1.2.3.4 nsmutabledictionary*dict = [NsmutabledictionaryNew]; [Dict setobject:_id Forkey:@"ID"]; [_notes addobject:dict]; } }//triggered when a string is encountered- (void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *)string{ //Replace carriage return and spaces string=[string stringbytrimmingcharactersinset: [Nscharacterset Whitespaceandnewlinecharacterset]]; if([stringIsequaltostring:@""]) { return; } nsmutabledictionary *dict = [_notes lastobject]; parsed in the order of the XML, so here is the correctif([_currenttagname isequaltostring:@"CDate"] &&dict) {[Dict setobject:stringForkey:@"CDate"]; } if([_currenttagname isequaltostring:@"Content"] &&dict) {[Dict setobject:stringForkey:@"Content"]; } if([_currenttagname isequaltostring:@"UserID"] &&dict) {[Dict setobject:stringForkey:@"UserID"]; }}//departure When the end tag is met- (void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString*) NamespaceURI qualifiedname: (NSString*) QName; {Self.currenttagname=Nil;}//trigger parse completion at end of document, return data to presentation layer, clean variables- (void) Parserdidenddocument: (Nsxmlparser *) parser{[[Nsnotificationcenter Defaultcenter] Postnotificationname:@"reloadviewnotification" Object: Self.notes Userinfo:nil]; Self.notes=Nil;}
3 parsing the use of XML documents Tbxml
Using DOM mode, third-party framework
Prepare: Download Tbxml and press to add the frameworks and libraries that tbxml depend on Foundation.framework uikit.framework coregraphics.framework libz.dylib
Add Project precompiled Header file mynotes-prefix.pch code for
#ifndef mynotes_prefixheader_pch #define MYNOTES_PREFIXHEADER_PCH#import <Foundation/Foundation.h> #define arc_enabled#endif
to configure a file in the project: Targets-build settings-apple LLVM 6.0 language-prefix Header Enter the file name you just created
Parse Start: Tbxml Class object Constructor-initwithstring:error:-initwithxmldata:error: Suitable for network communication resolution-INITWITHXMLFILE:ERROR:
//Start parsing-(void) start{_notes= [NsmutablearrayNew]; Constructor TBXML * Tbxml = [[Tbxml alloc] initwithxmlfile:@ "Notes.xml" Error:nil]; Gets the root element object of the document tbxmlelement * Root = tbxml.rootxmlelement; //if root element is valid if(Root) {tbxmlelement* Noteelement = [TBXMLchildelementnamed:@ "Note" Parentelement:root]; while(Noteelement! =Nil) {Nsmutabledictionary*dict = [NsmutabledictionaryNew]; Tbxmlelement*cdateelement = [TBXMLchildelementnamed:@ "CDate" parentelement:noteelement]; if(Cdateelement! =Nil) {NSString*cdate =[TBXML textforelement:cdateelement]; [Dict setvalue:cdate Forkey:@"CDate"]; } tbxmlelement*contentelement = [TBXML childelementnamed:@"Content"Parentelement:noteelement]; if(ContentElement! =Nil) {NSString*content =[TBXML textforelement:contentelement]; [Dict setvalue:content Forkey:@"Content"]; } tbxmlelement*useridelement = [TBXML childelementnamed:@"UserID"Parentelement:noteelement]; if(Useridelement! =Nil) {NSString*userid =[TBXML textforelement:useridelement]; [Dict setvalue:userid Forkey:@"UserID"]; } //Get id attributeNSString *_id = [TBXMLvalueofattributenamed:@ "id" forelement:noteelement Error:nil]; [Dict setvalue:_id Forkey:@"ID"]; [_notes addobject:dict]; noteelement = [TBXML nextsiblingnamed:@ "Note" Searchfromelement:noteelement]; }} NSLog (@"Parse Complete ..."); [[Nsnotificationcenter Defaultcenter] Postnotificationname:@"reloadviewnotification" Object: Self.notes Userinfo:nil]; Self.notes=Nil; }
4 JSON document Structure
Object: The "name-value" pair collection, similar to the dictionary type, {.. :。。 ,。。 :。。 ,。。 :。。 The name should be enclosed in double quotation marks.
Array: An ordered set of values, [,,,,], values can be any object string with double quotation marks, structure can be nested
5 JSON data parsing nsjsonserialization
- (void) viewdidload{[Super Viewdidload];NSString* Path = [[NSBundle mainbundle] Pathforresource:@"Notes"OfType:@"JSON"]; NSData *jsondata=[[NSData alloc] initwithcontentsoffile:path]; Nserror*error; Options specifies the schema enumeration that parses the JSON nsjsonreadingoptions:mutablecontainers specifies that the parse returns a mutable array or dictionary mutableleaves the specified leaf node is a mutable string allowfragments specifies that the top-level node may not be an array or dictionary
id jsonobj = [nsjsonserialization jsonobjectwithdata:jsondata options: Nsjsonreadingmutablecontainers error:&ERROR]; if(!jsonobj | |error) {NSLog (@"JSON decoding failed"); } self.objects= [jsonobj objectforkey:@ "Record"];}
IOS Development Guide Chapter 15th Accessing the Data Interchange Format for Web service