XML parsing of data parsing of iOS

Source: Internet
Author: User
Tags addchild parse error xpath

Two common ways of parsing xml: Dom parsing and sax parsing

Dom parsing

    • Dom:document Object Model (Document object type). When parsing XML, read through the entire XML document and build a tree structure (node tree) that resides in memory, which can be retrieved from any XML node, read its properties and values, and typically The XML node can be queried directly using XPath.
    • Parsing data in a DOM way requires the use of a third-party class Gdataxmlnode
    • Gdataxmlnode is an open source XML parsing class provided by Google, LIBXML2.TBD is objective-c encapsulated, capable of reading and writing to small or medium XML documents and supporting XPath syntax.
    • Gdataxmlnode How to use:
      1 Get the gdataxmlnode.h/m file and add the gdataxmlnode.h/m file to your project.
      2 Add the ' libxml2.tbd ' dynamic library to the project.
      3 in the "Build Settings" page of the project, locate the "Header Search Path" entry and add "/USR/INCLUDE/LIBXML2".
      4 Import the "GDataXMLNode.h" file to the head file, if the project can be compiled through, then the Gdataxmlnode added successfully.
      (Gdataxmlnode third party can search and download on github)

The parsing code is as follows:

-(void) xmldommethed{//Put all dictionaries in place   Self. Sourcearray= [NsmutablearrayArray];//SETP1. Get the data you need to parse   NSString*xmlpath = [[NSBundleMainbundle] pathforresource:@"Xmldemo"oftype:@"xml"];//step2. Converting to NSData typeNSData *xmldata = [NSData Datawithcontentsoffile:xmlpath];//step3.1 Building the Document object (options reserved parameters)Gdataxmldocument *doc = [[Gdataxmldocument alloc] initwithdata:xmldata options:0ErrorNil];//step3.2 Find root node (students)Gdataxmlelement *rootelement = [Doc rootelement];//step3.3 Find all child nodes of the root node   Nsarray*allsubnotes = [RootElement elementsforname:@"Student"];//step3.3 Find all child nodes of the student node    for(Gdataxmlelement *item in allsubnotes) {//Each time the loop starts, the description is a new student node, and we need a dictionary to hold all of its values        nsmutabledictionary*studentdic = [nsmutabledictionaryDictionary];//Get name node        Nsarray*namearray = [item elementsforname:@"Name"]; Gdataxmlelement *nameelement = [NameArray objectatindex:0];NSString*name = [Nameelement stringvalue]; [Studentdic setobject:name forkey:@"Name"];//Remove Age        Nsarray*agearray = [item elementsforname:@"Age"]; Gdataxmlelement *ageelement = [Agearray objectatindex:0];NSString*age = [Ageelement stringvalue]; [Studentdic setobject:age forkey:@"Age"];//Remove sex       Nsarray*sexarray = [item elementsforname:@"Sex"]; Gdataxmlelement *sexelement = [Sexarray objectatindex:0];NSString*sex = [Sexelement stringvalue]; [Studentdic setobject:sex forkey:@"Sex"];//Add the student dictionary to the array[ Self. SourcearrayAddobject:studentdic]; }NSLog(@"%@", Self. Sourcearray); }

Write the following code:

//Add nodes to XML through DOM parsing (sax can only read and cannot be added)- (void) domaddnote{//Get file path    NSString*xmlpath = [[NSBundleMainbundle] pathforresource:@"Xmldemo"oftype:@"xml"];//Convert files to data typeNSData *xmldata = [NSData Datawithcontentsoffile:xmlpath]; Gdataxmldocument *doc = [[Gdataxmldocument alloc] initwithdata:xmldata options:0ErrorNil]; Gdataxmlelement *rootelement = [Doc rootelement];//Create a node that we need to add (student)Gdataxmlelement *createelement = [Gdataxmlelement elementwithname:@"Student"];//Add properties to the student node[CreateElement addattribute:[gdataxmlelement attributewithname:@"attribute"stringvalue:@"AA"]];//Add child nodes to the student nodeGdataxmlelement *namenode = [Gdataxmlelement elementwithname:@"Name"stringvalue:@"Beautiful"];    [CreateElement Addchild:namenode]; Gdataxmlelement *agenode = [Gdataxmlelement elementwithname:@"Age"stringvalue:@" "];    [CreateElement Addchild:agenode]; Gdataxmlelement *sexnode = [Gdataxmlelement elementwithname:@"Sex"stringvalue:@"Male"]; [CreateElement Addchild:sexnode];//Creates a good student node and adds it to the root node, which is the students node[RootElement addchild:createelement];//Get all the student nodes    Nsarray*stuelementarray = [RootElement elementsforname:@"Student"];//Traversal to get each student node to get the value of the Student child node.      for(gdataxmlelement* item in Stuelementarray) {//Get the Attribute property value of the student node        NSLog(@"%@", [[Item attributeforname:@"attribute"] StringValue]);Nsarray*namearray = [item elementsforname:@"Name"]; Gdataxmlelement *nameelement = [NameArray objectatindex:0];NSString*name = [Nameelement stringvalue];//Remove Age        Nsarray*agearray = [item elementsforname:@"Age"]; Gdataxmlelement *ageelement = [Agearray objectatindex:0];NSString*age = [Ageelement stringvalue];//Remove sex        Nsarray*sexarray = [item elementsforname:@"Sex"]; Gdataxmlelement *sexelement = [Sexarray objectatindex:0];NSString*sex = [Sexelement stringvalue];NSLog(@"name=%@---age=%@----sex=%@", name,age,sex); }}

Sax parsing

    • The Sax:simple API for XML, based on event-driven parsing, parses the data row by line (using the protocol callback mechanism).
    • Nsxmlparser
      1 Nsxmlparser is an XML parsing class that comes with iOS, parsing data in sax mode
      2 parsing process callback by Nsxmlparserdelegate protocol method
      3 parsing process: Start tag---value--end tag
//遵循协议@interface rootViewController ()<NSXMLParserDelegate>//xml解析之sax解析
-(void) xmlsaxmethod{//Get the data you need to parse  NSString*xmlpath = [[NSBundleMainbundle] pathforresource:@"Xmldemo"oftype:@"xml"]; NSData *xmldata = [NSData Datawithcontentsoffile:xmlpath];//Create a tool class object for Sax parsingNsxmlparser *saxparser = [[Nsxmlparser alloc] initwithdata:xmldata];//Designated AgentSAXParser. Delegate= Self;//Start parsing sax parsing is a synchronous process  BOOLIsparse = [SAXParser parse];if(Isparse) {NSLog(@"Parse Complete"); }Else{NSLog(@"Parse failed"); }NSLog(@"I was at the end of the parsing.");}

Proxy method for pragma mark-sax parsing

//开始解析的代理方法-(void)parserDidStartDocument:(NSXMLParser *)parser {  NSLog(@"开始解析");  self.saxArray = [NSMutableArray array]; }
//Start parsing a node//elementname: Label name//namespaceuri: The link that the namespace points to//qname: Name of the namespace//attributedict: All properties of a node-(void) Parser: (nsxmlparser) parser didstartelement: (NSString) ElementName NamespaceURI: (NSString) NamespaceURI QualifiedName: (NSString) QName attributes: (nsdictionary<NSString*,NSString*> *) Attributedict {NSLog(@"Start parsing%@ node", elementname);When you start parsing the student tag, you should initialize the dictionary, because a dictionary corresponds to a student's information  if([ElementName isequaltostring:@"Student"]) { Self. Saxdic= [nsmutabledictionaryDictionary]; }}//Get the values between nodes-(void) Parser: (nsxmlparser) parser foundcharacters: (NSString) String {NSLog(@"Value--------%@", string);if( Self. valuestring) {//Description has value[ Self. valuestringAppendstring:string]; }Else{ Self. valuestring= [nsmutablestringStringwithstring:string]; }}//Node End value-(void) Parser: (nsxmlparser) parser didendelement: (NSString) ElementName NamespaceURI: (NSString) NamespaceURI QualifiedName: (NSString) QName {if([ElementName isequaltostring:@"Name"]) {//indicates that the name node has been evaluated to end[ Self. SaxdicSetObject: Self. valuestringForkey:elementname]; }if([ElementName isequaltostring:@"Age"]) {  [ Self. SaxdicSetObject: Self. valuestringForkey:elementname]; }if([ElementName isequaltostring:@"Sex"]) {  [ Self. SaxdicSetObject: Self. valuestringForkey:elementname]; }if([ElementName isequaltostring:@"Student"]) {  [ Self. SaxarrayAddObject: Self. Saxdic]; } Self. valuestring=Nil;//Empty  NSLog(@"End parsing of%@ nodes", elementname);}//End parsing-(void) Parserdidenddocument: (Nsxmlparser *) Parser {//data can be used to parse the completed  NSLog(@"%@", Self. Saxarray);NSLog(@"Entire parsing end");}//Parse error-(void) Parser: (nsxmlparser) parser parseerroroccurred: (Nserror) ParseError {NSLog(@"Parsing error-------%@", ParseError. Description);}

XML parsing of data parsing of iOS

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.