This article mainly introduces how to convert an XML file into an NSData object. For more information, see
NSData * xmlData = [[NSData alloc] initWithContentsOfFile: [NSString stringWithFormat: @ "% @/People. xml ", [[NSBundle mainBundle] resourcePath]; // 2. convert xmlData to the xml document GDataXMLDocument * xmlDocument = [[GDataXMLDocument alloc] initWithData: xmlData options: 0 error: nil]; // 3. obtain the node GDataXMLElement * rootElement = xmlDocument. rootElement; // 4. obtain the child node/* NSArray * elementArray = rootElement. children; // obtain the classone node GDataXMLElement * classoneElement = [elementArray firstObject]; for (GDataXMLElement * element in classoneElement. children) {// obtain the NSLog (@ "% @", element. stringValue); if (element. children. count> 0) {GDataXMLElement * infoElement = [element. children lastObject]; // obtain all attributes and attribute values of a node. NSArray * attArray = infoElement. attributes; for (GDataXMLElement * attElement in attArray) {// get the attribute name and attribute value NSLog (@ "% @-% @", attElement. name, attElement. stringValue) ;}}} * // fuzzy search NSArray * eArray = [rootElement nodesForXPath: @ "/info" error: nil]; NSLog (@ "% @", eArray );
Parsing xml NSData for iPhone Development
For details, refer to the code analysis below:
The xml string is:
// Parse button event-(IBAction) btnXml {NSString * str = [uitextview1 text]; // string to data NSData * xmlData = [str dataUsingEncoding: NSUTF8StringEncoding]; // NSXMLParser class is required for xml parsing. First, an NSXMLParser object is declared. // NSXMLParser * xmlRead = [[NSXMLParser alloc] initWithData: xmlData] is parsed. // initialize the NSXMLParser object [xmlRead setDelegate: self]; // set the NSXMLParser object resolution method proxy [xmlRead parse]; // call the proxy to parse the NSXMLParser object, check whether the resolution is successful} // The parser reads content from two nodes-(void) parser :( NSXMLParser *) parser foundCharacters :( NSString *) string {// NSLog (@ "% @", string) ;}// obtain the end value of the node-(void) parser :( NSXMLParser *) parser didEndElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName {// NSLog (@ "% @", elementName);} // obtain the end point value-(void) parser :( NSXMLParser *) parser didStartElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName attributes :( NSDictionary *) attributeDict {// NSLog (@ "% @", elementName); if ([elementName isinclutostring: @ "user"]) {NSString * strName = [attributeDict valueForKey: @ "name"]; NSString * strAge = [attributeDict valueForKey: @ "age"]; NSString * strUser = uitextview2.text; strUser = [strUser stringByAppendingFormat: @ "name: % @, age: % @ \ n ", strName, strAge]; [uitextview2 setText: strUser]; // NSLog (@" Name: % @, age: % @ ", strName, strAge );}}