XML parsing of IOS data parsing _ios

Source: Internet
Author: User
Tags addchild parse error tag name xpath


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



Dom parsing


    • Dom:document Object Model (Document object type). When parsing XML, it reads the entire XML document and constructs a tree structure (node tree) that resides in memory, through which you can retrieve any XML node, read its properties and values, and usually You can query XML nodes directly by using XPath.
    • DOM parsing data requires the use of a third party class Gdataxmlnode
    • Gdataxmlnode is an open source XML parsing class provided by Google, which encapsulates Libxml2.tbd objective-c, reads and writes to small or medium XML documents, and supports XPath syntax.
    • Gdataxmlnode Use Method:


1 Get the gdataxmlnode.h/m file and add the gdataxmlnode.h/m file to the project.



2 Add the ' libxml2.tbd ' dynamic library to the project.



3 on the Project Build Settings page, locate the Header Search Path entry and add "/USR/INCLUDE/LIBXML2".



4 Import "GDataXMLNode.h" file header file, if the project can be compiled, then gdataxmlnode add success.



(Gdataxmlnode third party can be downloaded in github search)



The parsing code is as follows:


-(void) xmlDOMMethed {

  // Hold all the dictionaries
 self.sourceArray = [NSMutableArray array];
  // setp1. Get the data that needs to be parsed
  NSString * xmlPath = [[NSBundle mainBundle] pathForResource: @ "XMLDemo" ofType: @ "xml"];
  // step2. Convert to NSData type
  NSData * xmlData = [NSData dataWithContentsOfFile: xmlPath];
  //step3.1 build document object (options reserved parameters)
  GDataXMLDocument * doc = [[GDataXMLDocument alloc] initWithData: xmlData options: 0 error: nil];
  //step3.2 find the root node (students)
  GDataXMLElement * rootElement = [doc rootElement];
 //step3.3 Find all children of the root node
  NSArray * allSubNotes = [rootElement elementsForName: @ "student"];
  //step3.3 Find all child nodes of the student node
  for (GDataXMLElement * item in allSubNotes) {

    // At the beginning of each loop, the description is a new student node.
    NSMutableDictionary * studentDic = [NSMutableDictionary dictionary];
    // 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 student dictionary to the array
    [self.sourceArray addObject: studentDic];
  }
NSLog (@ "% @", self.sourceArray);
 }


Write code as follows:


// Add nodes to xml through dom parsing (sax can only be read, not added)
-(void) domAddNote {
  // Get file path
  NSString * xmlPath = [[NSBundle mainBundle] pathForResource: @ "XMLDemo" ofType: @ "xml"];
  // Convert file to data type
  NSData * xmlData = [NSData dataWithContentsOfFile: xmlPath];

  GDataXMLDocument * doc = [[GDataXMLDocument alloc] initWithData: xmlData options: 0 error: nil];
  GDataXMLElement * rootElement = [doc rootElement];
  // Create a node (student) we need to add
  GDataXMLElement * createElement = [GDataXMLElement elementWithName: @ "student"];
  // Add attributes to the student node
  [createElement addAttribute: [GDataXMLElement attributeWithName: @ "attribute" stringValue: @ "aa"]];
  // Add child nodes to the student node
  GDataXMLElement * nameNode = [GDataXMLElement elementWithName: @ "name" stringValue: @ "美丽"];
  [createElement addChild: nameNode];
  GDataXMLElement * ageNode = [GDataXMLElement elementWithName: @ "age" stringValue: @ "18"];
  [createElement addChild: ageNode];
  GDataXMLElement * sexNode = [GDataXMLElement elementWithName: @ "sex" stringValue: @ "男"];
  [createElement addChild: sexNode];

  // Add the created student node to the root node, that is, under the students node
  [rootElement addChild: createElement];

  // Get all student nodes
  NSArray * stuElementArray = [rootElement elementsForName: @ "student"];

  / / Traverse to get each student node in order to get the value of the child node of the student.
  for (GDataXMLElement * item in stuElementArray) {

    // Get the attribute attribute 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


    • Sax:simple API for XML, based on event-driven parsing, parsing the data line by row (protocol callback mechanism).
    • Nsxmlparser


1 Nsxmlparser is a built-in XML parsing class for iOS, using sax to parse data



2 parsing process is recalled by Nsxmlparserdelegate protocol method



3 parsing process: start tag->-> end tag-> value


Follow the protocol
@interface Rootviewcontroller () <NSXMLParserDelegate>
Sax parsing FOR XML parsing
-(void) xmlsaxmethod{
 //Getting the data to be parsed
 nsstring *xmlpath = [[NSBundle Mainbundle] pathforresource:@ "Xmldemo" oftype:@ "xml"];
 NSData *xmldata = [NSData Datawithcontentsoffile:xmlpath];
 Create a Sax Parsing tool class object
 nsxmlparser *saxparser = [[Nsxmlparser alloc] initwithdata:xmldata];
 Specifies the agent
 saxparser.delegate = self;
 Start parsing sax Parsing is a synchronous process
 BOOL isparse = [SAXParser parse];
 if (isparse) {

   NSLog (@ "Parse complete");
 } else{
   NSLog (@ "Parse failed");
 }
 NSLog (@ "I am at the end of parsing");
}


Pragma mark-sax-resolved proxy methods


// Proxy method to start parsing
-(void) parserDidStartDocument: (NSXMLParser *) parser {
 NSLog (@ "Start parsing");
 self.saxArray = [NSMutableArray array];
}
// Start parsing a node
// elementName: tag name
// namespaceURI: the link pointed to by the namespace
// qName: the name of the namespace
// attributeDict: all attributes of the 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 starting to parse the student tags, you should initialize the dictionary, because a dictionary corresponds to a student's information
 if ([elementName isEqualToString: @ "student"]) {
   self.saxDic = [NSMutableDictionary dictionary];
 }
}
// Get the value between nodes
-(void) parser: (NSXMLParser) parser foundCharacters: (NSString) string {
 NSLog (@ "Value --------% @", string);
 if (self.valueString) {// Description has a value
   [self.valueString appendString: string];
 } else {
   self.valueString = [NSMutableString stringWithString: string];
 }
}
// end of a node


-(void) parser: (NSXMLParser) parser didEndElement: (NSString) elementName namespaceURI: (NSString) namespaceURI qualifiedName: (NSString) qName {
 if ([elementName isEqualToString: @ "name"]) {// Describes that the name node has been finished
 [self.saxDic setObject: self.valueString forKey: elementName];
 }
 if ([elementName isEqualToString: @ "age"]) {
 [self.saxDic setObject: self.valueString forKey: elementName];
 }
 if ([elementName isEqualToString: @ "sex"]) {
 [self.saxDic setObject: self.valueString forKey: elementName];
 }
 if ([elementName isEqualToString: @ "student"]) {
 [self.saxArray addObject: self.saxDic];
 }
 self.valueString = nil; // empty
 NSLog (@ "End the resolution of% @ node", elementName);
}


// End parsing


-(void) parserDidEndDocument: (NSXMLParser *) parser {
 // You can use the parsed data
 NSLog (@ "% @", self.saxArray);
 NSLog (@ "The end of the entire parsing");
}

// Parse error

-(void) parser: (NSXMLParser) parser parseErrorOccurred: (NSError) parseError {
 NSLog (@ "A parsing error occurred -------% @", parseError.description);
} 


The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.


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.