Tutorial on NSXMLParser parsing XML files for iPhone Development

Source: Internet
Author: User

IPhoneDevelopmentNSXMLParserAnalysisXmlThe document tutorial is the content to be introduced in this article. This article is mainly implemented by code. Let's look at the code.XmlThe file is as follows: Question. xml, which is placed in the Resource file directory.

 
 
  1. <? Xml version = "1.0" encoding = "UTF-8"?>
  2. <Root>
  3. <Question>
  4. <QuestionTitle> what are your academic scores? </QuestionTitle>
  5. <Answers>
  6. <Answer>
  7. <Result> the primary account has a good score. </Result>
  8. <Evaluate> you must answer your score truthfully. </Evaluate>
  9. </Answer>
  10. <Answer>
  11. <Result> probably in the middle-to-top level </Result>
  12. <Evaluate> If the score is not good, the reason should be stated. </Evaluate>
  13. </Answer>
  14. <Answer>
  15. <Result> excellent score, top in our class </Result>
  16. <Evaluate> the attitude towards learning should be serious. </Evaluate>
  17. </Answer>
  18. </Answers>
  19. </Question>
  20. </Root>
  21.  
  22. The IVPaserXMLSingleton. h file is as follows:
  23.  
  24. # Import <Foundation/Foundation. h>
  25. # Import "IVQuestionModel. h"
  26. # Import "IVAnswerModel. h"
  27.  
  28. @ Interface IVPaserXMLSingleton: NSObject {
  29. NSXMLParser * m_parser; // xml parsing class
  30. IVQuestionModel * m_queModel; // problem encapsulation class
  31. IVAnswerModel * m_ansModel; // encapsulation class of the answer
  32. NSMutableArray * m_arrXMLNode; // The encapsulated array list after xml Parsing
  33. }
  34.  
  35. // Method for achieving the single benefit
  36. + (IVPaserXMLSingleton *) GetInstance;
  37.  
  38. // Parse the xml file and encapsulate the parsed result into the list to return
  39. -(NSMutableArray *) GetArrayByPaserXML;
  40.  
  41. @ End
  42.  
  43. The IVPaserXMLSingleton. m file is a singleton class.
  44.  
  45. @ Implementation IVPaserXMLSingleton
  46.  
  47. Static IVPaserXMLSingleton * instance; // a singleton object
  48. BOOL flag = YES; // whether it is a repeated value assigned to a node
  49. NSString * m_strCurrentElement; // name of the read current node
  50.  
  51. + (IVPaserXMLSingleton *) GetInstance {
  52. @ Synchronized (self ){
  53. If (instance = nil ){
  54. Instance = [[self alloc] init];
  55. }
  56. }
  57. Return instance;
  58. }
  59.  
  60. -(NSMutableArray *) GetArrayByPaserXML {
  61. // Obtain the xml file
  62. NSString * pathpath = path = [[NSBundle mainBundle] pathForResource: @ "Question" ofType: @ "xml"];
  63. NSFileHandle * file = [NSFileHandle fileHandleForReadingAtPath: path];
  64. NSData * data = [file readDataToEndOfFile];
  65. [File closeFile];
  66.  
  67. M_parser = [[NSXMLParser alloc] initWithData: data];
  68.  
  69. // Set this class as a proxy class
  70. [M_parser setDelegate: self];
  71.  
  72. BOOL flag = [m_parser parse];
  73. If (flag ){
  74. NSLog (@ "succeeded in obtaining the xml file in the specified path ");
  75. } Else {
  76. NSLog (@ "failed to get the xml file in the specified path ");
  77. }
  78. [M_parser release];
  79. Return m_arrXMLNode;
  80. }
  81.  
  82. -(Void) parser :( NSXMLParser *) parser didStartElement :( NSString *) elementName
  83. NamespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName
  84. Attributes: (NSDictionary *) attributeDict {
  85. // Read the start label flag = YES
  86. Flag = YES;
  87.  
  88. // Record the currently resolved Node
  89. M_strCurrentElement = elementName;
  90.  
  91. //// Read the start tag of the xml and node.
  92. If ([elementName isEqualToString: @ "Root"]) {
  93. M_arrXMLNode = [[NSMutableArray alloc] init];
  94. }
  95.  
  96. // Parse the xml file for the interview question
  97. If ([m_xmlType isw.tostring: @ "Question"]) {
  98. If ([elementName isinclutostring: @ "Question"]) {
  99. M_queModel = [[IVQuestionModel alloc] init];
  100. M_queModel.m_arrAnswers = [[NSMutableArray alloc] init];
  101. } Else if ([elementName isinclutostring: @ "Answer"]) {
  102. M_ansModel = [[IVAnswerModel alloc] init];
  103. }
  104. }
  105. }
  106.  
  107. -(Void) parser :( NSXMLParser *) parser foundCharacters :( NSString *) string {
  108. If (flag ){
  109. // Parse the xml file for the interview question
  110. If ([m_xmlType isw.tostring: @ "Question"]) {
  111. If ([m_strCurrentElement isinclutostring: @ "QuestionTitle"]) {
  112. M_queModel.m_strQuestionTitle = string;
  113. } Else if ([m_strCurrentElement isinclutostring: @ "Result"]) {
  114. M_ansModel.m_strResult = string;
  115. } Else if ([m_strCurrentElement isinclutostring: @ "Evaluate"]) {
  116. M_ansModel.m_strEvaluate = string;
  117. }
  118. }
  119. }
  120. }
 
 
  1. -(Void) parser :( NSXMLParser *) parser didEndElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName {
  2. // Read the end label flag = NO
  3. Flag = NO;
  4.  
  5. // Parse the xml file for the interview question
  6. If ([m_xmlType isw.tostring: @ "Question"]) {
  7. If ([elementName isinclutostring: @ "Question"]) {
  8. [M_arrXMLNode addObject: m_queModel];
  9. [[M_queModel m_arrAnswers] release];
  10. [M_queModel release];
  11. M_queModel = nil;
  12. }
  13. If ([elementName isinclutostring: @ "Answer"]) {
  14. [[M_queModel m_arrAnswers] addObject: m_ansModel];
  15. [M_ansModel release];
  16. M_ansModel = nil;
  17. }
  18. }
  19. }
  20.  
  21. -(Void) parserDidStartDocument :( NSXMLParser *) parser {
  22. NSLog (@ "Start parsing xml files ");
  23. }
  24.  
  25. -(Void) parserDidEndDocument :( NSXMLParser *) parser {
  26. NSLog (@ "xml file parsed ");
  27. }
  28. @ End

The general process is like this. Common problems:

1. If an xml file fails to be read, the xml file format may be incorrect. Open the xml file with ie in the window to quickly check whether the xml file format is incorrect.

2. If the node value is too long, such as <Result>... </Result> if there is a long piece of content in the middle, the parsing process will cut the content into several segments for reading, namely:-(void) parser :( NSXMLParser *) parser foundCharacters :( NSString *) the string method will be repeatedly called until all the content is read, so if you use: m_ansModel.m_strResult = string; in this way, assign values, the result is incomplete. The solution is to use the NSMutableString type to receive the read value, like this:

 
 
  1. if (m_ansModel.m_strResult == nil) {   
  2. m_ansModel.m_strResult = [[NSMutableString alloc] initWithString:string];   
  3. } else {   
  4. [m_ansModel.m_strResult appendString:string];   
  5. }  

M_strResult is of the NSMutableString type. OK.

The above is my summary and I hope it will help you.

Summary:IPhoneDevelopmentNSXMLParserAnalysisXMLThe content of the document tutorial is complete. I hope this article will help you!

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.