SlideShare ist ein Scribd-Unternehmen logo
1 von 19
iOS XML Parser
 Evan Johnson - Boniface Designs
Objective


Create and iPhone application that downloads
and parses XML data
Steps


Create our XML Data

Create a View-based Application
XML File
XML: Extensible Markup Language, a metalanguage that
allows users to define their own customized markup
languages.



  My XML file will contain the following:
    Root Element: <element>
    Child Element: <elements>
   Attribute: myData
XML File
 <?xml version=”1.0”?>
 <elements>
 <element myData=”XML Parsed Successfully” />
 </elements>


I am going to save this file as “xmltest.xml” and upload it to my server. If
you want, you can skip creating an XML file and use mine. It is located at:

http://www.bonifacedesigns.com/tuts/xmltest.xml
iOS Methods

NSURLConnection
The NSURLConnection will allow us to download the XML file and
communicate with the server.


NSXML Parser
The NSXMLParser methods will help us access the data stored in the
XML file.


      Delegate: NSXMLParserDelegate
iOS Properties

NSMutableData
We will create an NSMutableData object to store the XML data that we
download


UILabel
I will present the downloaded data in a label on the applications screen


UIButton
A UIButton tap action will start the connection to download the XML
data
Steps
Now that we have created our app, we need
to make a connection to load our XML data.
We will do that with the following:

  NSURLRequest
  I will store the following connection data in a NSURLRequest object:
  URL Path to XML file, cache policy, and the timeout interval.


  NSURLConnection
  After creating the NSURLRequest object, I will initiate my connection
Make the request
 // Request data from URL
 NSURLRequest *theRequest = [NSURLRequest requestWithURL:
 [NSURL URLWithString:[NSString stringWithFormat:@"http://
 www.bonifacedesigns.com/tuts/xmltest.xml"]]
 
 
   
 
 
 
 
 
 
 
 
 
 cachePolicy:NSURLRequestUseProtocolCachePolicy
 
 
   
 
 
 
 
 
 
 
 
 timeoutInterval:60.0];




Above is the NSURLRequest. Notice that the request utilizes a URL from a
string. The URL is where the XML file I created earlier is hosted. I am using
default settings for the cache policy and time out interval.
Start the connection
    // Start loading data
    NSURLConnection *theConnection = [[NSURLConnection alloc]
    initWithRequest:theRequest delegate:self];
    if (theConnection) {
         // Create the NSMutableData to hold data
    
 receivedData = [[NSMutableData data] retain];
    } else {
    
 // Inform the user the connection failed.
    }


Now I need to allocate the NSURLConnection and check if it was created. If so,
I will create my NSMutableData object to hold any data that I receive. If not,
you can call upon another method and/or inform the user.

I am going to place this code and the NSURLRequest code in a method that
will be called when my UIButton is tapped.
Connection Response
     Received
 - (void)connection:(NSURLConnection *)connection
 didReceiveResponse:(NSURLResponse *)response



This response is usually received before any data has been loaded. I am
going to reset my NSMutableData object encase the server reset in the
middle of of my connection.
Connection Received
       Data
 - (void)connection:(NSURLConnection *)connection
 didReceiveData:(NSData *)data



Our XML data might be loaded incrementally. This response is called
whenever data is loaded. I need to append this data to my NSMutableData
object.
Connection Failed!
        (uh-oh)
 - (void)connection:(NSURLConnection *)connection
 didFailWithError:(NSError *)error



When a connection fails, this method will be called. We need to release our
connection, release our NSMutableData object, and possibly inform the
user.
Connection Finished

 - (void)connectionDidFinishLoading:(NSURLConnection
 *)connection



If everything works properly and our data is successfully loaded, this
method will be called. We need to initiate our parser (which I will do in a
separate method), and release our connection.
Steps


Create our data parser

Parse our data

Handle the data
Initiate our parser

 NSXMLParser *dataParser = [[NSXMLParser alloc]
 initWithData:receivedData];



In a method I will create (called startParsingData:), I will initiate the XML
parser with the method above. I will also assign a delegate to the parser
(self), tell the parser to parse my data, release the parser, and release the
NSMutableData object containing my data.
Parse Our Data
 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString
 *)elementName namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName attributes:(NSDictionary
 *)attributeDict



The above method will be called once our data is parsed. The method
gives us access to a number of variables, but we are mainly interested in
the elementName and attributeDict. The elementName is where we can
access the XML root and/or child element names. The attributeDict is a
NSDictionary that will store all of the attributes for our elements.
Parser Failed

 - (void)parser:(NSXMLParser *)parser parseErrorOccurred:
 (NSError *)parseError




The above method will be called if the parser has any errors. If the parser
fails, you can then notify the user and/or call upon another method. We
will just be notifying the user with the UILabel we created earlier.
Finally, connect
      everything up

 Open up our xib file and add a UIButton and
UILabel. Connect these objects to their respective
                   IBOutlets.

Weitere ähnliche Inhalte

Andere mochten auch

COGITO Classic Tutorial (Android)
COGITO Classic Tutorial (Android)COGITO Classic Tutorial (Android)
COGITO Classic Tutorial (Android)Cookoo Tips
 
iOS Development - A Beginner Guide
iOS Development - A Beginner GuideiOS Development - A Beginner Guide
iOS Development - A Beginner GuideAndri Yadi
 
SAP CRM Technical Course Content
SAP CRM Technical Course ContentSAP CRM Technical Course Content
SAP CRM Technical Course ContentChoodamani Infotech
 
Introduction to iOS Development
Introduction to iOS DevelopmentIntroduction to iOS Development
Introduction to iOS DevelopmentAsim Rais Siddiqui
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The BasicsJeff Fox
 

Andere mochten auch (8)

COGITO Classic Tutorial (Android)
COGITO Classic Tutorial (Android)COGITO Classic Tutorial (Android)
COGITO Classic Tutorial (Android)
 
iOS Development - A Beginner Guide
iOS Development - A Beginner GuideiOS Development - A Beginner Guide
iOS Development - A Beginner Guide
 
SAP CRM Technical Course Content
SAP CRM Technical Course ContentSAP CRM Technical Course Content
SAP CRM Technical Course Content
 
Introduction to iOS Development
Introduction to iOS DevelopmentIntroduction to iOS Development
Introduction to iOS Development
 
Json
JsonJson
Json
 
Apple iOS Report
Apple iOS ReportApple iOS Report
Apple iOS Report
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Apple iOS
Apple iOSApple iOS
Apple iOS
 

Kürzlich hochgeladen

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Kürzlich hochgeladen (20)

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

iOS XML Parsing Tutorial

  • 1. iOS XML Parser Evan Johnson - Boniface Designs
  • 2. Objective Create and iPhone application that downloads and parses XML data
  • 3. Steps Create our XML Data Create a View-based Application
  • 4. XML File XML: Extensible Markup Language, a metalanguage that allows users to define their own customized markup languages. My XML file will contain the following: Root Element: <element> Child Element: <elements> Attribute: myData
  • 5. XML File <?xml version=”1.0”?> <elements> <element myData=”XML Parsed Successfully” /> </elements> I am going to save this file as “xmltest.xml” and upload it to my server. If you want, you can skip creating an XML file and use mine. It is located at: http://www.bonifacedesigns.com/tuts/xmltest.xml
  • 6. iOS Methods NSURLConnection The NSURLConnection will allow us to download the XML file and communicate with the server. NSXML Parser The NSXMLParser methods will help us access the data stored in the XML file. Delegate: NSXMLParserDelegate
  • 7. iOS Properties NSMutableData We will create an NSMutableData object to store the XML data that we download UILabel I will present the downloaded data in a label on the applications screen UIButton A UIButton tap action will start the connection to download the XML data
  • 8. Steps Now that we have created our app, we need to make a connection to load our XML data. We will do that with the following: NSURLRequest I will store the following connection data in a NSURLRequest object: URL Path to XML file, cache policy, and the timeout interval. NSURLConnection After creating the NSURLRequest object, I will initiate my connection
  • 9. Make the request // Request data from URL NSURLRequest *theRequest = [NSURLRequest requestWithURL: [NSURL URLWithString:[NSString stringWithFormat:@"http:// www.bonifacedesigns.com/tuts/xmltest.xml"]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; Above is the NSURLRequest. Notice that the request utilizes a URL from a string. The URL is where the XML file I created earlier is hosted. I am using default settings for the cache policy and time out interval.
  • 10. Start the connection // Start loading data NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if (theConnection) { // Create the NSMutableData to hold data receivedData = [[NSMutableData data] retain]; } else { // Inform the user the connection failed. } Now I need to allocate the NSURLConnection and check if it was created. If so, I will create my NSMutableData object to hold any data that I receive. If not, you can call upon another method and/or inform the user. I am going to place this code and the NSURLRequest code in a method that will be called when my UIButton is tapped.
  • 11. Connection Response Received - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response This response is usually received before any data has been loaded. I am going to reset my NSMutableData object encase the server reset in the middle of of my connection.
  • 12. Connection Received Data - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data Our XML data might be loaded incrementally. This response is called whenever data is loaded. I need to append this data to my NSMutableData object.
  • 13. Connection Failed! (uh-oh) - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error When a connection fails, this method will be called. We need to release our connection, release our NSMutableData object, and possibly inform the user.
  • 14. Connection Finished - (void)connectionDidFinishLoading:(NSURLConnection *)connection If everything works properly and our data is successfully loaded, this method will be called. We need to initiate our parser (which I will do in a separate method), and release our connection.
  • 15. Steps Create our data parser Parse our data Handle the data
  • 16. Initiate our parser NSXMLParser *dataParser = [[NSXMLParser alloc] initWithData:receivedData]; In a method I will create (called startParsingData:), I will initiate the XML parser with the method above. I will also assign a delegate to the parser (self), tell the parser to parse my data, release the parser, and release the NSMutableData object containing my data.
  • 17. Parse Our Data - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict The above method will be called once our data is parsed. The method gives us access to a number of variables, but we are mainly interested in the elementName and attributeDict. The elementName is where we can access the XML root and/or child element names. The attributeDict is a NSDictionary that will store all of the attributes for our elements.
  • 18. Parser Failed - (void)parser:(NSXMLParser *)parser parseErrorOccurred: (NSError *)parseError The above method will be called if the parser has any errors. If the parser fails, you can then notify the user and/or call upon another method. We will just be notifying the user with the UILabel we created earlier.
  • 19. Finally, connect everything up Open up our xib file and add a UIButton and UILabel. Connect these objects to their respective IBOutlets.