How ios parses xml demo

How to parse xml files in ios

Two methods:1.the existing NSXMLParse class in IOs.

2.Google's GDataXML is also based on libxml2, so you need to import libxml2 before using GDataXML.

The following is a detailed explanation of nsxmlparse in ios:

NSxmlParser implements sax method to parse XML file.

The principle of dom implementation is to read the whole xml document at one time and put it in a tree structure. If necessary, find a specific node, and then read or write to it. His main advantages are simplicity and balance between reading and writing; The disadvantage is that it takes up more memory because it has to read the whole xml document into memory. The bigger the file, the more obvious this disadvantage is.

The implementation of Sax is different from dom. He only looks for the content with specific conditions in the xml document, and only extracts the required content. It takes up less memory and is flexible, which just meets our needs. His weakness is writing. Some materials introduce the writing, and I don't think this example is necessary.

Running NSXMLParser includes setting up, running and responding to the results.

1) starts NSXMLParser.

To use NSXMLParser, you must first create it and set various properties, mainly using the following methods:

InitWithContentsOfURL creates a parser through NSURL.

InitWithData creates a parser through NSData.

SetDelegate defines a delegate for the parser.

Parse runs the parser.

2) Act as a representative

The five most important methods:

//Handler for finding the beginning of an element (that is, reporting the beginning of an element and its attributes)

-(void) parser: (NSXMLParser *) parser

did startelement:(ns string *)element name

namespace uri:(ns string *)namespace uri

qualifiedName:(NSString *)qName

Attribute: (NSDictionary *)attributeDict

//The processing label contains content characters (all or part of the content of a report element)

-(void) parser: (NSXMLParser *) parser found the character: (NSString *) string.

//A handler for finding the terminator of an element, which saves the data of each item of the element (that is, the end tag of the reporting element).

-(void) parser: (NSXMLParser *) parser

didend element:(ns string *)element name

namespace uri:(ns string *)namespace uri

qualifiedName:(NSString *)qName

//End of report parsing

-(void) parser: (nsxml parser *) parser

//Report an unrecoverable parsing error

-(void)paser: a parser error occurred.

1. describes an xml processing protocol, which uses NSxmlParser protocol to process the XML file we want to parse, take out the required url and store it in the specified data.

*/

//Definition of multithreading class, method implementation, and sending back data to the main thread.

@ class AppRecord

//@ protocol ParseOperationDelegate;

@ protocol ParseOperationDelegate

-(void)did finish parsing:(NSArray *)appList;

-(void) parse error occurrence: (nserror *) error;

@end

@ interface parse operation:ns operation {

@ Private

id & lt& lt/span>。 ParseOperationDelegate & gt delegation; //,NSXMLParserDelegate

NSData * dataToParse

NSMutableArray * workingArray

AppRecord * workingEntry

NSMutableString * working property string;

NSArray * elementsToParse

BOOL stores storingCharacterData

}

-(id)initWithData:(NSData *) data delegation: (id < span class = "s13" > parseoperationdelegate & gt) the delegate.

@end

Then complete the initialization function of the protocol.

-(id)initWithData:(NSData *) data delegation: (id < span class = "s13" > parseoperationdelegate & gt) authorization

{

self =[super init];

If (ego! = zero)

{

self.dataToParse = data

self.delegate = theDelegate

self . elements parse =[NSArray array with objects:kIDStr,kNameStr,kImageStr,kArtistStr,nil];

}

Return to self;

}

2. Complete the parsing of specific tags.

# Miscellaneous note mark-

# Miscellaneous Note Tag RSS Processing

-(void) parser: (NSXMLParser *) parser didstartelement: (nsstring *) elementname

namespace uri:(ns string *)namespace uri

qualifiedName:(NSString *)qName

Attribute: (NSDictionary *)attributeDict

{

// entry: {id (link), im:name (application name), im:image (variable height)}

//

if([element name isEqualToString:kEntryStr])

{

self . working entry =[[[AppRecord alloc]init]auto release];

}

storingCharacterData =[elementsToParse contains object:element name];

}

3. Find the specific address and content and store it.

-(void) parser: (NSXMLParser *) parser didenelement: (nsstring *) elementname

namespace uri:(ns string *)namespace uri

qualifiedName:(NSString *)qName

{

if (self.workingEntry)

{

if (storingCharacterData)

{

ns string * trimmed string =[working property string stringbytrimmingcharacters inset:

[NSCharacterSet whitespace and newline characters et]];

[workingPropertyString set string:@ " "]; //Clear the string for the next time.

if([element name isEqualToString:kIDStr])

{

self . working entry . app urlstring = trimmed string;

}

else if([element name isEqualToString:kname str])

{

self . working entry . appname = trimmed string;

}

else if([element name isEqualToString:kImageStr])

{

self . working entry . imageurlstring = trimmed string;

}

else if([element name is equal tostring:kArtistStr])

{

self . working entry . artist = trimmed string;

}

}

else if([element name isEqualToString:kEntryStr])

{

[self . working array add object:self . working entry];

self.workingEntry = nil

}

}

}

-(void) parser: (NSXMLParser *) parser found the character: (NSString *) string.

{

if (storingCharacterData)

{

[workingPropertyString appendString:string];

}

}

Third-party solutions:::::::::

Introduction: Through the third-party assembly of KissXML, libxml2.dylib needs to be introduced.

(Also note that the runtime may prompt "libxml/tree.h not found".

Solution: Select a target among the targets of the project, switch to the building settings page on the right and search down.

Paths segment, in which there is a header search path item, and its value is set to: /usr/include/libxml2), as shown in the following figure:

The file format of ProvinceCity.xml is as follows:

The main code of this program is as follows:

# Import "DDXML.h"

# import " ddxmlelementadditions . h "

@ Implement View Controller

//parse XML

StaticNSString * kXML = @ "///District//Province ";

- (void)viewDidLoad

{

[superviewDidLoad];

ns string * path =[[NSString galloc]init withstring:[[NSBundlemainBundle]path for resource:@ " province city " of type:@ " XML "]];

ns data * data =[[NSDataalloc]initwithcontentsofile:path];

[self parseddata fromdata: dataandprovince: @ "Jiangxi Province"];

[self parseddatafromdata:data];

[data release];

}

//Take all the cities under a specific province.

-(void)parsedDataFromData:(ns data *)data and province:(ns string *)province {

ddxml document * doc =[[ddxml document alloc]initWithData:data options:0 error:nil];

////parse

NSArray * items =[docnodesForXPath:kxml error:nil];

for (DDXMLElement *objin items) {

DD xmlnode * aUser =[obj attribute for Name:@ " Name "]; //Take the value of the property name.

if([auser . stringvalueisequaltostring:province])

{

NSArray * City lst =[obj elements forname:@ " City "]; //Take the list of city points and save it in the array.

if(city lst . count & gt; 0)// Second floor

{

for(ddxml element * city in city lst){

DD xmlnode * citynode = [attribute for name of city: @ "name"];

NSLog(@“% @”,city node . string value);

}

}

}

}

[Document Release];

}

//Get all provinces and their subordinate nodes, including modification.

-(void)parsedDataFromData:(ns data *)data {

ddxml document * doc =[[ddxml document alloc]initWithData:data options:0 error:nil];

////parse

NSArray * items =[docnodesForXPath:kxml error:nil];

for (DDXMLElement *objin items) {

DD xmlnode * aUser =[objattributeForName:@ " Name "]; //Take the value of the property name.

//[aUser setStringValue:@ "Haha!" ]; //Modify the value of the attribute node

[objaddAttribute:[DDXMLNodeattributeWithName:@ " test " string value:@ " wzh "]]; //Add an attribute node

[objaddAttributeWithName:@ " TTT " string value:@ " 343 "]; //Add another attribute node.

//[obj setstring value:@ " new node "]; //Set the value of the current node

DDXMLNode * new node =[DDXMLNodeelementWithName:@ " new node "]; //Set a new node

[obj addChild:new node]; //Add a node to obj

ddxml element * newdxml =[[objelementsForName:@ " new node "]objectAtIndex:0]; //Access the node just added.

[newdxmladattributewithname:@ " node two " string value:@ " two value "]; //Add an additional subordinate node on the newly added node, which has another attribute value.

DDXMLNode * new node 2 =[DDXMLNodeelementWithName:@ " new node 2 " string value:@ " hello!" ];

[newdxmladchild:new node 2];

}

//Save to sandbox directory

ns string * path =[[NSStringalloc]initWithFormat:@“% @/XML data . XML],[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0]];

ns string * result =[[NSString alloc]initWithFormat:@“% @”,doc];

[resultwriteToFile:path atomically:yes encoding:nsu TF 8 string encoding error:nil];

//[result 2 write to file:path atomically:YES]; //This method won't work, there will be garbled codes after saving.

[Results release];

[Path release];

[Document Release];

}